I am either getting old or the queries that I need to write are getting more and more complicated. The following query will get all the tasks associated with the user.
"SELECT `date`
FROM `tasks`
WHERE `user_id`= 1;"
The tasks table is (id, date, user_id, url_id);
Now, I need to get as well records that url_id associates with the user trough the
`urls` table (`id`, `user_id`)
The standalone query would look like this:
"SELECT `t1`.`data`
FROM `tasks` `t1`
JOIN `urls` `u1` ON `u1`.`id` = `t1`.`url_id`
WHERE `u1`.user_id` = 1;"
Though, is it possible to merge these two queries into a single query? My logic says it should be, though I don't see how to do the actual JOIN.
I'd probably use a UNION.
SELECT `date`
FROM `tasks` WHERE `user_id`=1
UNION
SELECT `t1`.`date`
FROM `tasks` `t1`
INNER JOIN `urls` `u1` ON `u1`.`id` = `t1`.`url_id`
WHERE `u1`.user_id`=1;
You can do this in a single query:
SELECT t.date
FROM TASKS t
WHERE t.user_id = 1
OR EXISTS(SELECT NULL
FROM URLS u
WHERE u.id = t.url_id
AND u.user_id = 1)
However, OR is a notoriously bad performer -- it splinters the execution plan. Splitting the query, joining the result sets can be done using the UNION or UNION ALL operators. UNION removes duplicates from the final result set; UNION ALL does not remove duplicates and is faster for it.
SELECT t.date
FROM TASKS t
WHERE t.user_id = 1
UNION ALL
SELECT t.date
FROM TASKS t
WHERE EXISTS(SELECT NULL
FROM URLS u
WHERE u.id = t.url_id
AND u.user_id = 1)
Know your data, so you know which UNION operator best serves your needs.
Related
I am trying to find all of the users which do not have any orders.
So far I've tried the following:
select * from `users` where not exists
(select * from `orders` where `users`.`id` = `orders`.`user_id`)
I've also tried the following:
select users.*, count(distinct orders.reference) as orders_count from `users`
left join `orders` on `users`.`id` = `orders`.`user_id`
group by `users`.`id` having orders_count = 0
However, both are very slow running queries. There are around 5000 customers and 30,000+ orders. Is there a more efficient way of doing this?
You need to limit your subquery to only look at user_id. Also make sure user_id is indexed.
Alter table orders add index(user_id)
Select * from users where id NOT IN(select user_id from
orders)
I have a weird situation. I need to select all data from table name with distinct values from other table.
Here is database scheme of database that I need to get distinct values:
When I run both queries without INNER JOIN they run without error but when I use INNER JOIN I got error
This is query that I used:
SELECT * FROM `todo`
INNER JOIN
SELECT `task`.`status`,COUNT(*) as count FROM `task`
ON `todo`.`id`=`task`.`id_list` WHERE `todo`.`user_id` = 43
As you can see I need to get total count of status column from other table. Can it be done using one single query or do I need to run two querys to get data...
You need to wrap the join In parenthesis
SELECT td.*, t.*
FROM `todo` td
JOIN
( SELECT `status`, SUM(status=0) as status_0, SUM(status=1) as status_1 , id_list
FROM `task`
GROUP BY id_list
) t ON td.id= t.id_list
WHERE td.user_id = 43
You can do this in one query. Even without a subquery:
SELECT ta.status, COUNT(*) as count
FROM todo t INNER JOIN
task ta
ON t.id = ta.id_list
WHERE t.user_id = 43
GROUP BY ta.status;
EDIT:
If the above produces what you want, then you probably need:
SELECT t.*, ta.status, taa.cnt
FROM todo t INNER JOIN
task ta
ON t.id = ta.id_list INNER JOIN
(SELECT count(*) as cnt, ta.status
FROM task ta
GROUP BY ta.status
) taa
on ta.status = taa.status
WHERE t.user_id = 43 ;
You seem to want a summary at the status level, which is only in task. But you want the information at the row level for todo.
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 was wondering what is better in MySQL. I have a SELECT query that exclude every entry associated to a banned userID.
Currently I have a subquery clause in the WHERE statement that goes like
AND (SELECT COUNT(*)
FROM TheBlackListTable
WHERE userID = userList.ID
AND blackListedID = :userID2 ) = 0
Which will accept every userID not present in the TheBlackListTable
Would it be faster to retrieve first all Banned ID in a previous request and replace the previous clause by
AND creatorID NOT IN listOfBannedID
LEFT JOIN / IS NULL and NOT IN are fastest:
SELECT *
FROM mytable
WHERE id NOT IN
(
SELECT userId
FROM blacklist
WHERE blackListedID = :userID2
)
or
SELECT m.*
FROM mytable m
LEFT JOIN
blacklist b
ON b.userId = m.id
AND b.blackListedID = :userID2
WHERE b.userId IS NULL
NOT EXISTS yields the same plan but due to implementation flaws is marginally less efficient:
SELECT *
FROM mytable
WHERE NOT EXISTS
(
SELECT NULL
FROM blacklist b
WHERE b.userId = m.id
AND b.blacklistedId = :userID2
)
All these queries stop on the first match in blacklist (hence performing a semi-join)
The COUNT(*) solution is the least efficient, since MySQL will calculate the actual COUNT(*) rather than stopping on the first match.
However, if you have a UNIQUE index on (userId, blacklistedId), this is not much of problem as there cannot be more than one match anyway.
Use EXISTS clause to check for user not in blacklist.
Sample Query
Select * from userList
where not exists( Select 1 from TheBlackListTable where userID = userList.ID)
IN clause is used when there is fixed values or low count of values.
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
)