How can i select all the id's from a table, and let select all the songs with the id;s from the other table?
$query = "SELECT * FROM songs WHERE id = (SELECT songid FROM top10 order by id)'";
You can use IN for that (or EXISTS):
select *
from songs
where id in (
select songid
from top10 )
Based on your comments, you might actually be looking to use JOIN (just realize if there are duplicate records in the top10 table, this could return duplicate results):
select s.*
from songs s
join top10 t on s.id = t.songid
order by t.id
SQL Fiddle Demo
Related
I have an articles table that and I am displaying it in the homepage in a while loop. Inside the while loop I want to display the comments count and images count for each article.
It is working for me now, but it is three queries in total, I am trying to combine it in the first query and then just display all of them in one while loop. Here is what I am trying to achieve:Articles page
The current format I am following:
//a represents articles table, c represents comments table, i represents image table
$query = mysqli_query($conn, "SELECT a.a_id, a.title, a.datetime, a.user_id FROM a ORDER BY a.datetime DESC");
while($fetch = mysqli_fetch_assoc($query){
$imageQ = msqli_query($conn, "SELECT COUNT(image_path), image_path FROM i WHERE a_id = '$fetch['a_id']'");
$imageFetch = mysqli_fetch_assoc($imageQ);
$commentQ = mysqli_query($conn, "SELECT COUNT(comment_id) FROM c WHERE a_id = '$fetch['a_id']'");
$commentFetch = mysqli_fetch_assoc($commentQ);
}
I want to cram all of these queries into one single query that fetches the article and comments count and image count for each article and the first image.
The images and comments are separate dimensions of the data. So, you have to be careful about how to bring them together. In your case, you can aggregate the values before doing the joins:
SELECT a.a_id, a.title, a.datetime, a.user_id,
i.num_images, c.num_comments
FROM a LEFT JOIN
(SELECT a_id, COUNT(image_path) as num_images
FROM i
GROUP BY a_id
) i
ON i.a_id = a.a_id LEFT JOIN
(SELECT a_id, COUNT(comment_id) as num_comments
FROM c
GROUP BY a_id
) c
ON c.a_id = a.a_id
ORDER BY a.datetime DESC;
You can use mysql nested queries something like
SELECT a.,tab1.,tab2.* FROM a INNER JOIN (SELECT * FROM b ) as tab1 INNER JOIN (SELECT * FROM c) as tab2
Hope this can get you to get desired output.
Thanks
I have a data structure where students and groups have many-to-many relationship. I have three tables
students: id, name
groups: id, name
students_groups: student_id, group_id
How do I select only students who are not in a specific group (e.g. group.id = 1)?
I did some searching and tried using sub query but only get an empty set...
select * from students where not exists (select students.* from students left join students_groups on students_groups.student_id = student.id where students_groups.group_id = 1);
how should I query? thx much in advance!
EDIT
OK, it seems the following two finally works... can anyone EXPLAIN to me why I don't need to join table for it to work???
select * from students where not exists (select * from students_groups where students_groups.student_id = student.id and student_groups.group_id = 1);
select * from students where id not in (select student_id from students_groups where group_id = 1);
Using a NOT IN should work fine:
SELECT * FROM Students
WHERE Id NOT IN (
SELECT Student_Id FROM Students_Groups
WHERE Group_Id = 1)
The edited question asks for an explanation.
Think of SQL queries as Venn Diagrams in text. Each clause either defines a circle of content, or tells you which part of the full overlapping circles diagram you're interested in.
select * from students where id not in (select student_id from students_groups where group_id = 1);
One circle is the students table. One circle is the student_groups table where group_id = 1. The circles overlap where students.id equals student_groups.student_id. You want the part of the students table that is not in the overlap area.
You don't need to join the tables because your result set contains data only from the students table. You are using the other table to limit that result set, not provide data to your results.
Untested, but one of the following ought to work. You'll have to do some explaining and see which one is best.
select *
from students
where not exists (select *
from students_groups
where students_groups.student_id = student.id
and students_groups.group_id = 1)
or...
select *
from students
where id not in (select student_id
from students_groups
where group_id = 1)
or...
select students.id, students.name
from students
left outer join students_groups on students.id = students_groups.student_id
and students_groups.group_id = 1
where students_groups.student_id is null
group by students.id, students.name
You could try something like this:
SELECT
*
FROM
students
WHERE
id NOT IN
((SELECT
student_id
FROM
students_groups
WHERE
group_id = 1
))
I am trying to join my users table with another table using the following query...
SELECT * FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Is there any way to do the join so that the id of the user does not replace the id of the activity?
For example, currently if there is an activity with the id of 10 and the user 2 the id will be replaced by the id of the users table and show as 2 after I run the query.
Thanks a lot for the help!
Whenever you are joining tables, you ought to be explicit about the columns you select rather than using SELECT *, and specify column aliases for them when the same column name is used in multiple tables.
SELECT
activities.id,
activities.othercol,
/* Alias to userid */
users.id AS userid,
users.name,
users.anothercolumn
FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Though it isn't strictly necessary to prepend the table name to each, unless the column names are the same.
SELECT
activities.id AS activityid,
othercol,
users.id AS userid,
name,
anothercolumn
If I have a list of ID's that I have selected from a statement
SELECT id FROM myTable WHERE name = 'TEST'
This would return just the ids (1001, 1002, 1003, etc...) Then I want to perform another SELECT statement to retrieve all the titles for all those ids.
SELECT title FROM myTable2 WHERE id = XXXX
the id in table2 is the foreign key of table2. id in myTable is the Primary Key. How can I go about retrieving all the titles from those ids. I was thinking about storing all the results of the first select statement in an array, and then using a while loop to iterate through the list and return each result into another array, but my fear is that when the database gets big if it has to return 1000 rows that could be some bad overhead. So in PHP or SQL what is the best way to perform this?
You can use a subquery:
SELECT title
FROM myTable2
WHERE id IN (
SELECT id
FROM myTable
WHERE name = 'TEST'
)
Another way to do it would to be use a JOIN, to avoid the sub-query:
SELECT title
FROM myTable2
LEFT JOIN myTable
ON myTable.id = myTable2.id
WHERE myTable.name = 'TEST'
You should just be able to select them at the same time.
SELECT a.id, b.title
FROM myTable a, myTable2 b
WHERE a.name = 'TEST' AND b.id = a.id;
to select both:
SELECT id, title FROM mytable WHERE name="TEST"
or to select the whole row
SELECT * FROM mytable WHERE name="TEST"
if its two tables you are selecting from:
SELECT id, title FROM mytable A JOIN mytable2 B USING (id)
Hey guys I have a mysql table called interests with 4 columns. interestID, name, categoryID interest_desc and date. the categoryID column is linked to a seperate table. How would I use a mysql query that checked how many interests are in a certain category?
Im guessing i use some sort of count() query?
Thanks guys
Update -
$count_query_v1 = "SELECT categoryID, COUNT(*) AS total FROM interests GROUP by categoryID; "; $answer = mysql_query($count_query_v1) or die(mysql_error()); echo $answer;
Getting closer but still not perfect, i want to echo out the categoryID with the most interestID's
select category_name, count(*) as total
from interests i left join category c on c.category_id = i.category_id
group by i.category_id;
count + group by,
assuming interestID is the unique primary key,
and each interest is tied to single category (as what you have shown)
select categoryID, count(*) as total
from interests
group by categoryID;
// the above example is a simple group by ID without using inner join
output :-
categoryID, total
SELECT COUNT(interestID) FROM interests WHERE categoryID = 'yourvalue';
SELECT COUNT(interestID), categoryID FROM interests GROUP BY categoryID;
Since you are using the insert query each query will insert one record, so just count the number of insert queries you run by using a counter varialble.