I need to get the users age by his ID. Easy.
The problem is, at the first time I don't know their IDs, the only thing I know is that it is in a specific table, let's name it "second".
SELECT `age` FROM `users` WHERE `userid`=(SELECT `id` FROM `second`)
How can I do that?
SELECT age FROM users WHERE userid IN (SELECT id FROM second)
This should work
Your example
SELECT `age` FROM `users` WHERE `userid`=
(SELECT `id` FROM `second`
WHERE `second`.`name` = 'Berna')
should have worked as long as you add a where criteria. This is called subqueries, and is supported in MySQL 5. Reference http://dev.mysql.com/doc/refman/5.1/en/comparisons-using-subqueries.html
SELECT
age
FROM
users
inner join
Second
on
users.UserID = second.ID
An inner join will be more efficient than a sub-select
SELECT age FROM users WHERE userid IN (SELECT id FROM second)
but preferably
SELECT u.age FROM users u INNER JOIN second s ON u.userid = s.id
You want to use the 'in' statement:
select * from a
where x=8 and y=1 and z in (
select z from b where x=8 and active > '2010-01-07 00:00:00' group by z
)
Related
I need a fresh pair of eyes on this. I have two tables, one of which has users and the second which contains login records, multiple records for each user. What I'm trying to do is select all entries from the first table, and the most recent record from the second table, e.g., a list of all users but only show the most recent activity. Both tables have auto increment in the ID column.
My code currently is thus:
SELECT u.user_id, u.name, u.email, r.rid, r.user_id
FROM users AS u
LEFT JOIN login_records AS r ON r.user_id = u.user_id
WHERE
r.rid = (
SELECT MAX( rid )
FROM login_records
WHERE user_id = u.user_id
)
I've scoured answers to similar questions on SO and tried all of them, but results have been either returning nothing or only getting odd results (not necessarily the newest one). ID in both tables is auto-increment, so I thought it should be a relatively simple matter to get the only or highest ID for a particular user, but it either returns nothing or a completely different selection each time.
It's my first time using JOIN - do I have the wrong JOIN? Do I need to ORDER or GROUP things differently?
Thanks for your help. It's got to be something simple, since Danny Coulombe's answer appearing here seems to work for other users.
You will need a subquery I believe:
https://www.db-fiddle.com/f/2wudMDVxReYJz4FEyG19Va/0
CREATE TABLE users (
user_id INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE users_logins (
user_login_id INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED NOT NULL
);
INSERT INTO users SELECT 1;
INSERT INTO users SELECT 2;
INSERT INTO users_logins SELECT 1,1;
INSERT INTO users_logins SELECT 2,1;
INSERT INTO users_logins SELECT 3,1;
INSERT INTO users_logins SELECT 4,1;
INSERT INTO users_logins SELECT 5,2;
INSERT INTO users_logins SELECT 6,2;
And the query:
SELECT
u.user_id, ul.latest_login_id
FROM users u
LEFT JOIN
(
SELECT user_id, MAX(user_login_id) latest_login_id
FROM users_logins
GROUP BY user_id
) ul ON u.user_id = ul.user_id
You have to ORDER BY with what column you want to display by desc, for example ORDER BY last_login DESC.
Change the last_login column with the column you want to order, but you must first declare the last_login column after SELECT.
How about replacing all rid in where clause and corrolated subquery by record_id?
SELECT u.user_id, u.name, u.email, r.rid, r.record_id, r.user_id
FROM test_users AS u
LEFT JOIN test_login_records AS r ON r.user_id = u.user_id
WHERE
(r.record_id = (
SELECT MAX(record_id)
FROM test_login_records
WHERE user_id = u.user_id
) OR r.record_id is null);
Test here
Why I get #1060 - Duplicate column name 'id'
SELECT COUNT(*) FROM (SELECT * FROM `tips` `t` LEFT JOIN
tip_usage ON tip_usage.tip_id=t.id GROUP BY t.id) sq
Probably because the * in select * selects two columns with the same name from tip_usage and tips.
Probably it's because the inner select yields two columns with the name id. Since you are not using those columns, you can just change the select to:
SELECT COUNT(*) FROM (SELECT t.id FROM `tips` `t`
LEFT JOIN tip_usage ON tip_usage.tip_id=t.id
GROUP BY t.id) sq
Your query is equivalent to this:
SELECT COUNT(DISTINCT id)
FROM tips
, there is no need in a join.
Are you sure you didn't want an INNER JOIN instead?
Had the same problem, renaming into select clause saved me
SELECT people.id, vehicle.id ...
I renamed it with AS keyword
SELECT people.id AS person_id, vehicle.id ...
I have multiple tables as table_1 has id , p_code, profile_status, name and table_2 has id, p_code, availablity and table_3 has id, p_code, status...
How to get all records form all tables depend on p_code.
table_2 and table_3 has few records. if p_code not in table_2 and table_3 then echo 'no' in results.
currently i am using my query as below
select t.id, t.p_code,t.name,t.num_rooms, t.profile_status, t.distance FROM (
( SELECT id , p_code, profile_status, name,num_rooms, 3956 * 2 * ASIN(SQRT( POWER(SIN(($origLatAirport - latitude)*pi()/180/2),2)
+COS($origLatAirport*pi()/180 )*COS(latitude*pi()/180)
*POWER(SIN(($origLonAirport-longitude)*pi()/180/2),2)))
as distance FROM property WHERE profile_status=1 having distance < ".$dist." ) ) as t
How to add table_2 and table_3 and fetch results.
Pleasr reply soon. I am stuck here.
In your query you are doing CROSS JOIN and what you desire, is probably INNER JOIN.
In MySQL the CROSS JOIN behaves like JOIN and INNER JOIN of without using any condition.
The CROSS JOIN returns all rows form user multiplied by all rows from user_inbox - for every user you get inboxes of all users.
You should specify condition for your JOIN statement.
$sql_alt = mysql_query(
"select i.*,u.images, u.firstname, u.lastname
from user_inbox i INNER JOIN user u ON i.to_id = u.user_id
where i.to_id = '$user_id'");
Also it is good habit have the same names for primary and foreign keys, so I think you should have user_id or user_id_to instead of to_id in your user_inbox table. This is of course not absolutely necessary.
I wanna run a subquery that uses the value of the outer query in its where clause. Here's and example of what I wanna do:
SELECT * FROM `tbl1`
WHERE `tbl1`.`max_count` < (
SELECT COUNT(*) rc FROM `tbl2`
WHERE `tbl2`.`id` = `tbl1`.`id
)
There is tbl1 with a column named max_count, and there is tbl2 with rows referring to a row in tbl1(many-to-one relationship). What I wanna do is select rows in tbl1 where the number of rows in tbl2 referencing it is less than the max_count value of that row. But I'm pretty sure that what I wrote here, ain't gonna cut it. Any ideas?
Thanks a lot
try this -
SELECT * FROM `tbl1` t1
WHERE t1.`max_count` < (
SELECT COUNT(*) FROM `tbl2` t2
WHERE t2.`id` = t1.`id`
)
try using JOIN.
SELECT DISTINCT a.*
FROM tb1 a
INNER JOIN
(
SELECT id, COUNT(*) totalCount
FROM tbl2
GROUP BY id
) b ON a.ID = b.ID
WHERE a.max_count < b.totalCount
As an alternate solution, it's probably easier to just use a LEFT JOIN with HAVING than a subquery;
SELECT tbl1.*, COUNT(tbl2.id) current_count
FROM tbl1
LEFT JOIN tbl2
ON tbl1.id=tbl2.id
GROUP BY tbl1.id
HAVING COUNT(tbl2.id) < max_count
An SQLfiddle to test with.
Note that the GROUP BY in this case is a MySQL only thing, normally you'd need to GROUP BY every selected field in tbl1 even if tbl1.id is known to be unique per row.
I have 2 tables. MySql
users : A_ID,name
event : B_ID, A_ID,cat_id,date
Now I want to get all users , who participated more at events on a given period of time, and need to add based on category too. I am doing something like this :
select name from users ,
(select A_id, count(*)
from event
where date<=givendate
group by A_id
order by count(*) desc ) e
where users.A_id=e.a_id
limit 0,5
Is there any easy and prof way to write that script ?
Thanks
Your query looks OK apart from a few minor points:
Your ORDER BY and LIMIT should be in the outer select otherwise the order of the results is indeterminate.
Use the JOIN keyword to join two tables.
Try this:
SELECT u.name
FROM users AS u
JOIN
(
SELECT A_id, COUNT(*) AS cnt
FROM event
WHERE date <= givendate
AND cat_id = 42
GROUP BY A_id
) AS e
USING (A_id)
ORDER BY e.cnt DESC
LIMIT 5