counting lines in a table using user-defined variable from another table? - count

I'm very new to this - could someone let me know if this query is correct? I'm trying to take a variable from table 1 and use it to count lines in table 2...
Many thanks.
INSTRUCTION
Take the following hypothetical 2 table database:
Table 1, called content, has the fields: content_id, content_name, content_url.
Table 2, called views, has the following fields: view_id, content_id, view_timestamp
Write a MySQL query to find the total number of views for a piece of content with the content_name "maria_video".
MY QUERY
mysql> SELECT #ID:=content_id FROM content WHERE content_name=”maria_video”;
mysql> COUNT(*) FROM views WHERE content_id=#ID;

Based on this
Write a MySQL query to find the total number of views for a piece of content with the content_name "maria_video".
Couldn't you just write a single query that gets the same value?
Something like this
SELECT COUNT(*) FROM Views AS v INNER JOIN Content AS c ON (v.content_id=c.content_id) WHERE c.content_name="maria_video"
I don't have a mysql instance available to test it right now, but it should work.

Related

{SQLITE3} How can I force a query to not use a index on a given table?

I am doing performance analysis over mondial database using sqlite3. One test case where I have to compare performance with and without using index (it should not use sqlite_autoindex as well).
I found this link :How can I force a query to not use a index on a given table? very useful but most of the answers refer to SQL SERVER. But I need it for SQLITE3. (I have tried PRAGMA options but no result).
It's buried in the syntax diagrams for SELECT, but there is a way - Using NOT INDEXED with a table name in the FROM clause:
sqlite> CREATE TABLE foo(bar);
sqlite> CREATE INDEX foo_idx ON foo(bar);
sqlite> EXPLAIN QUERY PLAN SELECT * FROM foo WHERE bar = ?;
QUERY PLAN
`--SEARCH TABLE foo USING COVERING INDEX foo_idx (bar=?)
sqlite> EXPLAIN QUERY PLAN SELECT * FROM foo NOT INDEXED WHERE bar = ?;
QUERY PLAN
`--SCAN TABLE foo
As you can see, the first query uses the index, and the second one doesn't.
How to read EXPLAIN QUERY PLAN output.

I have to update one table field as another field of different table in sql

I have to update one table field as another field of different table in sql. There are two tables, create_account and Trans_Details. I have to update amount field of create_account table and set it into current_balance of Trans_Details table. How can I join these two tables? please write a query for this.
You can utilize the sub queries to do this...
Example:
I do not know what kind of data base r u using i am just giving a pseudo code..
UPDATE create_account SET (amount) = ( SELECT current_balance FROM Trans_Details
WHERE filter = some_value) WHERE filter = some_value.
I have added the where clause in the query, please ignore if u want to update the entire row in the column amount.

SQL Subquery and CAST not working

I am trying to get data from one table which is in varchar form and pass the same to other query which has same field as int.
Table Article with following fields
(ArticleID int, ArticleTitle nvarchar(200), ArticleDesc nvarchar(MAX))
Sample data
1 Title1 Desc1
2 Title2 Desc2
3 Title3 Desc3
I have another Table called Banner which has banner related to Articles
(BannerID int, BannerName nvarchar(200), BannerPath nvarchar(MAX), ArticleID varchar(200))
Sample Data
**BannerID BannerName BannerFile ArticleID**
100 Banner1 BannerPath1 '1','3','5'
101 Banner2 BannerPath2 '2','3','5'
102 Banner3 BannerPath3 '8','3','5'
103 Banner4 BannerPath4 '10','30','5','2','3','5'
Sample Query
SELECT ArticleTitle
FROM Article
WHERE CAST(ArticleID AS varchar(200)) IN (
SELECT ArticleID FROM Banner WHERE BannerID = 2
)
In my actual project i have multiple fields in banner table so that i can assign banner article, writer, Category, Pages..
For this reason i decided to store ArticleID or WriteID or CatID as single field in this format'10','30','5','2','3','5'
I change my structure then i may end up create hundreds of records for one banner and one banner can be assigned to any one of this article, writer, Category, Pages
Query below return zero rows may be my casting is creating problem I would appreciate how i can get arounds this without changing my database structure
SELECT ArticleTitle FROM Article WHERE CAST(ArticleID AS varchar(200)) IN (SELECT ArticleID FROM Banner WHERE BannerID = 2)
UPDATED:
No offense to any one i have decided to stick to my design as the question i had asked was for backed reporting section of the website which won't be used to often. I can be wrong regarding not normalizing the tables ...
My actual scenario Suppose users visit url
`abc.com/article/article.aspx?articleID=30&CatID=10&PageID=3&writerID=3`
Based on this url i can run four queries with UNION to get the required banner off-course i have to decide on banner precedence so i will do it like this
`SELECT BannerName, BannerImage FROM Banner WHERE ArticleID LIKE '%''30''%'`
UNION ALL
`SELECT BannerName, BannerImage FROM Banner WHERE CategoryID LIKE '%''10''%'`
UNION ALL
`Another query .......`
If i do it this way then query will have to look for banners in single table with few rows But if i normalize table based on JW which is good way of doing it may result in 30-40 rows for each banner in different table which may effect performance as i have to add new banner for new articles (for new magazine issues).
I know i am breaking every law of normalizing but i am afraid i have to do it for performance as i may end up having 2000 rows for every 100 banners & this will grow with time.
Updated Again
I hope this image will give you an over view of what i am trying to do
If i do it this way then i only need 1 row per banner & if i further normalize and create more table then i might end up having several row for one banner for example
Taking above image sample from banner table then my first banner will have 27 Rows
Second Banner 11 Rows
Thirds Banner 14 rows.
In order to avoid this i thought of to store multiple articleID, IssueID, PageID .... in their respected fields. This approach might be dirty but it is working.
I Definitely had some -ve feedback which from their point of view is understandable.. Since i have provided further details is my approach totally unprofessional or it is fine keeping in mind that website might have very good traffic & this approach may be faster.
It is a very bad design when you have saved comma separated values in a column when these values will be used in searching of records.
You need to properly normalize and restructure the table into 3-table design because I can see a Many-to-Many relationship on Article and Banner.
Suggested Schema design:
Article Table
ArticleID (PK)
ArticleTitle
ArticleDesc
Banner Table
BannerID (PK)
BannerName
BannerPath
Article_Banner Table
ArticleID (FK) (Also a compound PK with BannerID)
BannerID (FK)
and by this design you can simply query your records like:
SELECT a.*
FROM Article a
INNER JOIN Article_Banner b
ON a.ArticleID = b.ArticleID
WHERE b.BannerID = 2
advantages of the structure:
can easily create query statements
can take advantage of the indexes defined
etc..
In additio to John Woo's excellent answer, I will try to answer the question "Why doesn't the query return any results".
I'm going to leave aside the WHERE b.BannerID = 2 clause, which is obviously not met by any of the sample records.
The main issue with the query is the IN clause. IN will tell you whether an item is found in a set of items. What you are expecting it to do is iterate through a set of sets and tell you whether the item is found.
To illustrate this, here are two simplified queries:
-- this will print 0
if '1' in ('''1'',''3'',''5''')
print 1
else
print 0
-- this will print 1
if '1' in ('1', '3', '5')
print 1
else
print 0
The main point is that IN is a set-based operation, not a string function that will find a substring.
One possible solution to your problem would be to use CHARINDEX to perform the substring detection:
select ArticleTitle
from Article a
join Banner b
on charindex(CAST(a.ArticleID AS varchar(200)), b.ArticleID) > 0
This version is incorrect, because searching for the id '1' will also match values like '11','12'.
In order to get correct results, you could end up with a query similar to this (in order to make sure you only match on values between asterisks):
select ArticleTitle
from Article a
join Banner b
on charindex('''' + CAST(a.ArticleID AS varchar(200)) + '''', b.ArticleID) > 0
SQLFiddle: http://www.sqlfiddle.com/#!3/2ee3c/23
This query, however, has two big disadvantages:
it gets awfully slow for relatively big tables, as it cannot use any indexes and needs to scan the Banner table for each row in Article
the code got a little bit more complex and the more functionality you'll add to it, the harder it will get to reason about it, resulting in maintainability problems.
These two problems are smells that you are doing something wrong. Following JW's solution will get rid of the two problems.
Fully agree the above example is bad and not the correct way for what he is doing. However the root error message issue still exist and is a problem under some conditions.
My situation is working with a table to hold some custom form field element data. Without laying out the entire structure I’ll just lay out what is needed to show and reproduce the issue. I can also confirm the issue resolves around the IsNumeric in this case. Combined with the SubQueries as well. The sample holds two items, item name simulating the custom field element/type and the field value. Some are names, and some are minutes of labor. Could be weights, temps, distances, whatever, it’s customer definable extra data.
Create Table dboSample (cKey VarChar(20), cData VarChar(50))
Insert Into dboSample (cKey, cData) Values ('name', 'Jim')
Insert Into dboSample (cKey, cData) Values ('name', 'Bob')
Insert Into dboSample (cKey, cData) Values ('labortime', '60')
Insert Into dboSample (cKey, cData) Values ('labortime', '00')
Insert Into dboSample (cKey, cData) Values ('labortime', '15')
Select * From (Select * From dboSample Where IsNumeric(cData) = 1) As dboSampleSub Where Cast(cData As Int) > 0
Resulting in an error “Conversion failed when converting the varchar value 'Jim' to data type int.”
The lower nested query has a where clause limiting returned rows to only included numeric based data. However the cast in the higher level is clearly seeing rows not included in the sub query return. It is in fact seeing and processing data of the lower nested query. Cannot locate an Select OPTION flags to prevent this.

MS Access 2010 Triggers/data macros

I am developing a database to do a annual inventory count with 32 tables in it, 33 including the Master.
We currently have 4000 SKU's so the master table needed to be broken down into smaller tables so I can hand out a realistic amount of work to my counters.
What I am trying to achive is when my counters enter data in the smaller tables using the UI it would automatically populate the fields in the master table.
Any help would be greatly appreciated.
Michael
In Access, there is no way to apply a trigger to a table. What you can do is create a form that implements a grid. Have an After-Update event fire that does what you need. You can make the form look like a table by using the datasheet view.
While you can create a data macro* to update a table from an update on another, why would you want to do it in this case? You can either include the quantity field in the sub table and validate the data against the main table before running an update query, or the sub table (note, table, the employee ID will be sufficient to divide the data) could consist only of an employee id and an SKU, the sub table can then be joined to the main table by SKU and all updates use the quantity field from the main table:
SELECT Mytable1.SKU, MyTable.Quantity
FROM MyTable1
INNER JOIN MyTable
ON MyTable1.SKU = MyTable.SKU
WHERE EmployeeID = [Enter ID: ]
*Data Macro

Hierarchical Database Select / Insert Statement (SQL Server)

I have recently stumbled upon a problem with selecting relationship details from a 1 table and inserting into another table, i hope someone can help.
I have a table structure as follows:
ID (PK) Name ParentID<br>
1 Myname 0<br>
2 nametwo 1<br>
3 namethree 2
e.g
This is the table i need to select from and get all the relationship data. As there could be unlimited number of sub links (is there a function i can create for this to create the loop ?)
Then once i have all the data i need to insert into another table and the ID's will now have to change as the id's must go in order (e.g. i cannot have id "2" be a sub of 3 for example), i am hoping i can use the same function for selecting to do the inserting.
If you are using SQL Server 2005 or above, you may use recursive queries to get your information. Here is an example:
With tree (id, Name, ParentID, [level])
As (
Select id, Name, ParentID, 1
From [myTable]
Where ParentID = 0
Union All
Select child.id
,child.Name
,child.ParentID
,parent.[level] + 1 As [level]
From [myTable] As [child]
Inner Join [tree] As [parent]
On [child].ParentID = [parent].id)
Select * From [tree];
This query will return the row requested by the first portion (Where ParentID = 0) and all sub-rows recursively. Does this help you?
I'm not sure I understand what you want to have happen with your insert. Can you provide more information in terms of the expected result when you are done?
Good luck!
For the retrieval part, you can take a look at Common Table Expression. This feature can provide recursive operation using SQL.
For the insertion part, you can use the CTE above to regenerate the ID, and insert accordingly.
I hope this URL helps Self-Joins in SQL
This is the problem of finding the transitive closure of a graph in sql. SQL does not support this directly, which leaves you with three common strategies:
use a vendor specific SQL extension
store the Materialized Path from the root to the given node in each row
store the Nested Sets, that is the interval covered by the subtree rooted at a given node when nodes are labeled depth first
The first option is straightforward, and if you don't need database portability is probably the best. The second and third options have the advantage of being plain SQL, but require maintaining some de-normalized state. Updating a table that uses materialized paths is simple, but for fast queries your database must support indexes for prefix queries on string values. Nested sets avoid needing any string indexing features, but can require updating a lot of rows as you insert or remove nodes.
If you're fine with always using MSSQL, I'd use the vendor specific option Adrian mentioned.

Resources