JOINING TWO SQL statements - mysql

I appologise for the NOOB question, but I just can't get my head around JOINING results from two tables.
I have one table (tableA) that links entries with categories has the columns entry_id and cat_id
I have another table (tableB) that counts the number of times entry_id has been viewed against a timestamp
I want to get a list of entry_id's from tableB sorted by the number of times they have been viewed and filtered by cat_id from tableA.
I have the two SQL statements, but can't figure out how to put them together.
Statement 1 - Get entry_id's within a particular category:
SELECT entry_id FROM tableA WHERE cat_id = ""
Statement 2 - Get a sorted list of entry_id's from tableB:
SELECT entry_id FROM tableB GROUP BY entry_id ORDER BY COUNT(*) DESC
Thanks!

SELECT
tableb.entry_id,
FROM
tableb
INNER JOIN tablea
ON tableb.entry_id = tablea.entry_id
AND tablea.cat_id = ""
GROUP BY
tableb.entry_id
ORDER BY
COUNT(*) DESC

Try this:
SELECT
A.entry_id, Count(B.entry_id) Viewed
FROM TableA A
LEFT JOIN TableB B
ON A.entry_id = B.entry_id
WHERE A.Cat_Id = 5 -- your cat_id
GROUP BY A.entry_id
ORDER BY Count(B.entry_id) DESC

Related

Keep all records in "WHERE IN()" clause, even if they are not found

I have the following mysql query:
SELECT id, sum(views) as total_views
FROM table
WHERE id IN (1,2,3)
GROUP BY id
ORDER BY total_views ASC
If only id 1,3 are found in the database, i still want id 2 to appear, with total_views being set to 0.
Is there any way to do that? This cannot use any other table.
This query hard-codes the list of possible IDs using a sub-query consisting of unions... it then left joins this set of ids to the table containing the information to be counted.
This will preserve an ID in your results even if there are no occurrences:
SELECT ids.id, sum(views) as total_views
FROM (
SELECT 1 AS ID
UNION ALL SELECT 2 AS ID
UNION ALL SELECT 3 AS ID
) ids
LEFT JOIN table
ON table.ID = ids.ID
GROUP BY ids.id
ORDER BY total_views ASC
Alternately, if you had a numbers table, you could do the following query:
SELECT numbers.number, sum(views) as total_views
FROM
numbers
LEFT JOIN table
ON table.ID = ids.ID
WHERE numbers.number IN (1, 2, 3)
GROUP BY numbers.number
ORDER BY total_views ASC
Here's an alternative to Micheal's solution (not a bad solution, mind you -- even with "a lot" of ID's), so long as you're not querying against a cluster.
create temporary table __ids (
id int unsigned primary key
) engine=MEMORY;
insert into __ids (id) values
(1),
(2),
(3)
;
SELECT table.id, sum(views) as total_views
FROM __ids left join table using (id)
GROUP BY table.id
ORDER BY total_views ASC
And if your query becomes complex, I could even conceive of it running more efficiently this way. But, if I were you, I'd benchmark this option with Michael's ad-hoc UNION'ed table option using real data.
in #Michael's answer, if you do have a table with the ids you care about, you can use it as "ids" in place of Michael's in-line data.
Check this fiddle... http://www.sqlfiddle.com/#!2/a9392/3
Select B.ID, sum(A.views) sum from tableB B
left outer join tableA A
on B.ID = A.ID
group by A.ID
also check
http://www.sqlfiddle.com/#!2/a1bb7/1
try this
SELECT id
(CASE 1
IF EXISTS THEN views = mytable.views END
IF NOT EXIST THEN views = 0 END
CASE 2
IF EXISTS THEN views = mytable.views END
IF NOT EXIST THEN views = 0 END
CASE 3
IF EXISTS THEN views = mytable.views END
IF NOT EXIST THEN views = 0 END), sum(views) as total_views
FROM mytable
WHERE id IN (1,2,3)
GROUP BY id
ORDER BY total_views ASC
Does it have to be rows or could you pivot the data to give you one row and a column for every id?
SELECT
SUM(IF (id=1, views, 0)) views_1,
SUM(IF (id=2, views, 0)) views_2,
SUM(IF (id=3, views, 0)) views_3
FROM table

SQL - selecting userid which has max number of not null rows in a different table

I've 3 tables say A,B,C.
Table A has userid column.
Table B has caid column.
Table C has lisid and image columns.
one userid can have one or several caids.
one caid can have one or several lisids.
how do I select a userid which has maximum number of rows with image column as not null (in some lisids image column is blank and in some it has some value).
can someone please help.
Presumably, the ids are spread among the tables in a reasonable fashion. If so, the following should do this:
select b.userid, count(*)
from TableB b join
TableC c
on b.caid = c.caid
where c.image is not null
group by b.userid
order by count(*) desc
limit 1
The question in the comments is how you connect TableA to TableB and TableB to TableC. The reasonable approach is to have the userid in TableB and the caid in TableC.
Getting all the rows with the max requires a bit more work. Essentially, you have to join in the above query to get the list
select s.*
from (select b.userid, count(*) as cnt
from TableB b join
TableC c
on b.caid = c.caid
) s
(select count(*) as maxcnt
from TableB b join
TableC c
on b.caid = c.caid
group by b.userid
order by count(*) desc
limit 1
) smax
on s.cnt = smax.cnt
Other databses have a set of functions called window functions/ranking functions that make this sort of query much simpler. Alas, MySQL does not offer these.

Selecting rows with unique field values in mysql

I have these columns for table comments:
id
content
add_date
uid
school_id
Rows can have the same school_id.
I want to select the latest data according to add_date, but only 1 row per school_id (no duplicate for school_id) with limit of 10.
I've tried many codes already and its not working for me.
Any help would be appreciated.
This is what we call Greatest N per Group. You can achieved this by putting into a subquery so it can be joined against the non-grouped table (comments).
Try this:
SELECT c.*
FROM
(
SELECT school_id, MAX(add_date) maxDate
FROM comments
GROUP BY school_id
) x INNER JOIN comments c
ON x.school_id = c.school_ID AND
x.maxDate = c.add_date
ORDER BY x.maxDate desc
LIMIT 10
select C.ID, C.Content, t1.MaxDate as [add_date], C.uid, t1.school_id
from (selet school_id, max(add_Date) as 'MaxDate'
from comments
group by school_id) T1
inner join comments C on T1.school_id = C.school_id and C.add_Date= T1.MaxDate
LIMIT 10
If you want to choose which 10 rows return, add an order by, or a Where clause
select c1.*
from comments c1
where add_date = (select max(add_date) from comments c2 where c2.school_id =c1.school_id)
order by add_date desc
limit 10
create indexes on comments(add_date) and comments(school_id, add_date)

Mysql can't join two tables columns into one show

I want to show two columns summarize data.
table1 - count all fields that the id same as the id on the show_users table.
table2 - sum all values that the id same as the id on the show_users table.
This is my query:
SELECT show_users.id, COUNT(`table1`.id) as sum_fields , SUM(`table2`.count) as count_all
FROM `show_users`
LEFT JOIN `table1` ON `show_users`.id = `table1`.id
LEFT JOIN `table2` ON `show_users`.id = `table2`.id
GROUP by show_users.id
ORDER BY sum_fields DESC
The table2 results are fine, but the table1 count isn't correct values...
Why is that?
SELECT show_users.id, COUNT(DISTINCT `table1`.id) as sum_fields , SUM(`table2`.count) as count_all

Mysql Select within IF condition

looking to perform a query that on a particular conditions gets the data from another table.
it like
select field1, field2.... IF(fieldX=3,select value from sub_table where cat_id = 3 order by id desc limit 0,1, NULL) from abc ;
The query within the if is valid.
I am used to with implementing if conditions without any issue but those were all for some static values or a field. But, this is the first time I am trying to get a select's result in if and unable to do it.
The case is because for some particular value of 'fieldX' I need to get a record from another table.
Regards
Junaid
wrap you inner select in ( )
IF(fieldX=3, (select value from sub_table where cat_id = 3 order by id desc limit 0,1), NULL)
why not use a left join and use fieldX=3 as a join condition? if fieldX is different from 3, sql fills the field with NULL
select a.field1, a.field2, sub.value
from abc a
left join
(
select value from sub_table
where cat_id = 3
limit 0,1
) sub
on a.fieldX = 3
or, if you do want to get all rows for the corresponding values (i see you have cat_id = 3 and fieldX = 3, so basically cat_id = fieldX), just use a simple join. no need to use complicated if constructs. sql was built to do fast and efficient joins:
select a.field1, a.field2, sub.value
from abc a
left join sub_table sub
on a.fieldX = sub.cat_id
note however, that the second query will return multiple rows, when there are more matches between fieldX and cat_id (non-unique cat_id)
you could do something like:
select fields... from sub_table st
where st.idSubTable in(
Select IF(fieldX=3
,(
select st.idSubTable from sub_table where cat_id = 3 order by id desc limit 0,1
),
NULL)
from abc);
it will solve your problem.