How can I combine four queries into one query? - mysql

Structure of my tables:
posts (id, name, user_id, about, time)
comments (id, post_id, user_id, text, time)
users_votes (id, user, post_id, time)
users_favs ( id, user_id, post_id, time)
How can I combine these four queries (not with UNION):
SELECT `id`, `name`, `user_id`, `time` FROM `posts` WHERE `user_id` = 1
SELECT `post_id`, `user_id`, `text`, `time` FROM `comments` WHERE `user_id` = 1
SELECT `user`, `post_id`, `time` FROM `users_votes` WHERE `user` = 1
SELECT `user_id`, `post_id`, `time` FROM `users_favs` WHERE `user_id` = 1
Should I use JOINs?
What would the SQL query for this be?

You don't want to join these together.
The kind of JOIN you'd use to retrieve this would end up doing a cross-product of all the rows it finds. This means that if you had 4 posts, 2 comments, 3 votes, and 6 favorites you'd get 4*2*3*6 rows in your results instead of 4+2+3+6 when doing separate queries.
The only time you'd want to JOIN is when the two things are intrinsically related. That is, you want to retrieve the posts associated with a favorite, a vote, or a comment.
Based on your example, there's no such commonality in these things.

Related

Insert into multiple selects from different tables

I have tables users (id, email), permissions (id, description) and users_permissions (user_id, permission_id, created) with many to many relation.
I need to select user with some email and assign to him all permissions from table permissions, which he does not have.
Now I am trying to assign at least all permissions, but I am getting error
Subquery returns more than 1 row
My query:
insert into `users_permissions` (`user_id`, `permission_id`, `created`)
select
(select `id` from `users` where `email` = 'user-abuser#gmail.com') as `user_id`,
(select `id` from `permissions`) as `permission_id`,
now() as `created`;
If a subquery (inside SELECT) returns more than one row, MySQL does not like it.
Another way to achieve your requirement is using CROSS JOIN between Derived Tables (subquery in the FROM clause):
INSERT INTO `users_permissions` (`user_id`, `permission_id`, `created`)
SELECT
u.id,
p.id,
NOW()
FROM
users AS u
CROSS JOIN permissions AS p
WHERE u.email = 'user-abuser#gmail.com'

Selecting parent records when child mathes criteria

I am trying to limit returned results of users to results that are "recent" but where users have a parent, I also need to return the parent.
CREATE TABLE `users` (
`id` int(0) NOT NULL,
`parent_id` int(0) NULL,
`name` varchar(255) NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `times` (
`id` int(11) NOT NULL,
`time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `users`(`id`, `parent_id`, `name`) VALUES (1, NULL, 'Alan');
INSERT INTO `users`(`id`, `parent_id`, `name`) VALUES (2, 1, 'John');
INSERT INTO `users`(`id`, `parent_id`, `name`) VALUES (3, NULL, 'Jerry');
INSERT INTO `users`(`id`, `parent_id`, `name`) VALUES (4, NULL, 'Bill');
INSERT INTO `users`(`id`, `parent_id`, `name`) VALUES (5, 1, 'Carl');
INSERT INTO `times`(`id`, `time`) VALUES (2, '2019-01-01 14:40:38');
INSERT INTO `times`(`id`, `time`) VALUES (4, '2019-01-01 14:40:38');
http://sqlfiddle.com/#!9/91db19
In this case I would want to return Alan, John and Bill, but not Jerry because Jerry doesn't have a record in the times table, nor is he a parent of someone with a record. I am on the fence about what to do with Carl, I don't mind getting the results for him, but I don't need them.
I am filtering tens of thousands of users with hundreds of thousands of times records, so performance is important. In general I have about 3000 unique id's coming from times that could be either an id, or a parent_id.
The above is a stripped down example of what I am trying to do, the full one includes more joins and case statements, but in general the above example should be what we work with, but here is a sample of the query I am using (full query is nearly 100 lines):
SELECT id AS reference_id,
CASE WHEN (id != parent_id)
THEN
parent_id
ELSE null END AS parent_id,
parent_id AS family_id,
Rtrim(last_name) AS last_name,
Rtrim(first_name) AS first_name,
Rtrim(email) AS email,
missedappt AS appointment_missed,
appttotal AS appointment_total,
To_char(birth_date, 'YYYY-MM-DD 00:00:00') AS birthday,
To_char(first_visit_date, 'YYYY-MM-DD 00:00:00') AS first_visit,
billing_0_30
FROM users AS p
RIGHT JOIN(
SELECT p.id,
s.parentid,
Count(p.id) AS appttotal,
missedappt,
billing0to30 AS billing_0_30
FROM times AS p
JOIN (SELECT missedappt, parent_id, id
FROM users) AS s
ON p.id = s.id
LEFT JOIN (SELECT parent_id, billing0to30
FROM aging) AS aging
ON aging.parent_id = p.id
WHERE p.apptdate > To_char(Timestampadd(sql_tsi_year, -1, Now()), 'YYYY-MM-DD')
GROUP BY p.id,
s.parent_id,
missedappt,
billing0to30
) AS recent ON recent.patid = p.patient_id
This example is for a Faircom C-Tree database, but I also need to implement a similar solution in Sybase, MySql, and Pervasive, so just trying to understand what I should do for best performance.
Essentially what I need to do is somehow get the RIGHT JOIN to also include the users parent.
NOTES:
based on your fiddle config I'm assuming you're using MySQL 5.6 and thus don't have support for Common Table Expressions (CTE)
I'm assuming each name (child or parent) is to be presented as separate records in the final result set
We want to limit the number of times we have to join the times and users tables (a CTE would make this a bit easier to code/read).
The main query (times -> users(u1) -> users(u2)) will give us child and parent names in separate columns so we'll use a 2-row dynamic table plus a case statement to to pivot the columns into their own rows (NOTE: I don't work with MySQL and didn't have time to research if there's a pivot capability in MySQL 5.6)
-- we'll let 'distinct' filter out any duplicates (eg, 2 'children' have same 'parent')
select distinct
final.name
from
-- cartesian product of 'allnames' and 'pass' will give us
-- duplicate lines of id/parent_id/child_name/parent_name so
-- we'll use a 'case' statement to determine which name to display
(select case when pass.pass_no = 1
then allnames.child_name
else allnames.parent_name
end as name
from
-- times join users left join users; gives us pairs of
-- child_name/parent_name or child_name/NULL
(select u1.id,u1.parent_id,u1.name as child_name,u2.name as parent_name
from times t
join users u1
on u1.id = t.id
left
join users u2
on u2.id = u1.parent_id) allnames
join
-- poor man's pivot code:
-- 2-row dynamic table; no join clause w/ allnames will give us a
-- cartesian product; the 'case' statement will determine which
-- name (child vs parent) to display
(select 1 as pass_no
union
select 2) pass
) final
-- eliminate 'NULL' as a name in our final result set
where final.name is not NULL
order by 1
Result set:
name
==============
Alan
Bill
John
MySQL fiddle

MySQL Select from UNION performance issue (kills database)

I have a little problem regarding MySQL
I'm trying to make a UNION of two tables like so:
SELECT `user_id`, `post_id`, `requested_on`
FROM `a`
WHERE `status` != 'cancelled'
UNION
SELECT `user_id`, `post_id`, `time` as requested_on
FROM `b`
WHERE `type` = 'ADD'
This query is executed in Showing rows 0 - 29 (36684 total, Query took 0.0147 sec)
but when I do
SELECT * FROM (
SELECT `user_id`, `post_id`, `requested_on`
FROM `a`
WHERE `status` != 'cancelled'
UNION
SELECT `user_id`, `post_id`, `time` as requested_on
FROM `b`
WHERE `type` = 'ADD'
) tbl1
MySQL dies.
The reason why I want to do this is to GROUP BY user_id, post_id
Any ideas why this happens / any workarounds?
later-edit:
This is the SQL Fiddle:
http://sqlfiddle.com/#!2/c7f82d/2
The final query is there, which executes in:
Record Count: 10; Execution Time: 574ms
574ms for 10 records in my point of view is gigantic.
I found what the problem was from.
It was the fact that I was running the queries in PHPMyAdmin and when I did a SELECT UNION SELECT everything was good but when I did
SELECT * FROM (SELECT UNION SELECT)
the pagination system from PHPMyAdmin failed, and PHPMyAdmin was trying to output to my browser a over 30k rows table, that's why the SQL Request hang. :(
It is not clear what the question:
SELECT * FROM (
SELECT user_id, post_id, requested_on
FROM a
WHERE status != cancelled
UNION
SELECT user_id, post_id, time as requested_on
FROM b
WHERE type = ADD
) tbl1 GROUP BY user_id, post_id
means. Assume you have:
A, x, t1
A, x, t2
would you like the row with t1 or t2? If that does not matter lets apply an aggregate function such as MIN:
SELECT user_id, post_id, MIN(requested_on) FROM (
SELECT user_id, post_id, requested_on
FROM a
WHERE status <> cancelled
UNION
SELECT user_id, post_id, time as requested_on
FROM b
WHERE type = ADD
) tbl1
GROUP BY user_id, post_id
MySQL usually doesn't handle derived tables like this very well, is there any other predicate that you can apply to the parts in the union?

SQL command doesn't return rows

I have a SQL command which I know data exists with the criteria, but when I run the query it doesn't return rows:
SQL:
SELECT `USER_ID`, `CAR_ID`, `AD_ID`, `BRAND`, `MODEL`
, `YEAR`, `PRICE`, `MILEAGE`, `GEARBOX`, `STATUS`, `COLOR_IN`, `COLOR_OUT`
, `BODY`, `FUEL`, `ABOUT`, `MAIN_PHOTO`
FROM (`ads`, `cars`, `ad_extras`)
WHERE `ads`.`USER_ID` = '2'
What should I do?
EDIT:
When I do SELECT * it also doesn't return data.
when I select from 2 tables it retaurns data. So I can't select from 3 tables right?
It's likeky that one of your tables is empty. The result of that is empty.You should use a query like this one
SELECT `USER_ID`, `CAR_ID`, `AD_ID`, `BRAND`, `MODEL`, `YEAR`, `PRICE`, `MILEAGE`, `GEARBOX`, `STATUS`, `COLOR_IN`, `COLOR_OUT`, `BODY`, `FUEL`, `ABOUT`, `MAIN_PHOTO` FROM `ads` natural left join `cars` natural left join `ad_extras` WHERE `ads`.`USER_ID` = '2'
I wanted to post this like a comment but I don't have enought privilegies.
In order to query from 3 table it is better to use JOIN clause between them
or if you want to write it as it is use alias for selecting columns
e.g
SELECT 'ads.USER_ID', 'cars.CAR_ID', 'ads.AD_ID'
FROM ('ads', 'cars', 'ad_extras')
WHERE 'ads'.'USER_ID' = '2'
with their respective table

Aggregate function not working as expected with subquery

Having some fun with MySQL by asking it difficult questions.
Essentially i have a table full of transactions, and from that i want to determine out of all the available products (productid), who (userid) has bought the most of each? The type in the where clause refers to transaction type, 1 being a purchase.
I have a subquery that on its own returns a list of the summed products bought for each person, and it works well by itself. From this i am trying to then pick the max of the summed quantities and group by product, which is a pretty straight forward aggregate. Unfortunately it's giving me funny results! The userid does not correspond correctly to the reported max productid sales.
select
`userid`, `productid`, max(`sumqty`)
from
(select
`userid`, `productid`, sum(`qty`) as `sumqty`
from
`txarchive`
where
`type` = 1
group by `userid`,`productid`) as `t1`
group by `productid`
I have removed all the inner joins to give more verbal results as they don't change the logic of it all.
Here is the structure of tx if you are interested.
id bigint(20) #transaction id
UserID bigint(20) #user id, links to another table.
ProductID bigint(20) #product id, links to another table.
DTG datetime #date and time of transaction
Price decimal(19,4) #price per unit for this transaction
QTY int(11) #QTY of products for this transaction
Type int(11) #transaction type, from purchase to payment etc.
info bigint(20) #information string id, links to another table.
*edit
Working final query: (Its biggish)
select
`username`, `productname`, max(`sumqty`)
from
(select
concat(`users`.`firstname`, ' ', `users`.`lastname`) as `username`,
`products`.`name` as `productname`,
sum(`txarchive`.`qty`) as `sumqty`
from
`txarchive`
inner join `users` ON `txarchive`.`userid` = `users`.`id`
inner join `products` ON `txarchive`.`productid` = `products`.`id`
where
`type` = 1
group by `productname`,`username`
order by `productname`,`sumqty` DESC) as `t1`
group by `productname`
order by `sumqty` desc
Not the best solution (not even guaranteed to work 100% of the times):
select
`userid`, `productid`, max(`sumqty`)
from
( select
`userid`, `productid`, sum(`qty`) as `sumqty`
from
`txarchive`
where
`type` = 1
group by
`productid`
, `userid`
order by
`productid`
, `sumqty` DESC
) as `t1`
group by
`productid`