I have two tables - incoming tours(id,name) and incoming_tours_cities(id_parrent, id_city)
id in first table is unique, and for each unique row from first table there is the list of id_city - s in second table(i.e. id_parrent in second table is equal to id from first table)
For example
incoming_tours
|--id--|------name-----|
|---1--|---first_tour--|
|---2--|--second_tour--|
|---3--|--thirth_tour--|
|---4--|--hourth_tour--|
incoming_tours_cities
|-id_parrent-|-id_city-|
|------1-----|---4-----|
|------1-----|---5-----|
|------1-----|---27----|
|------1-----|---74----|
|------2-----|---1-----|
|------2-----|---5-----|
........................
That means that first_tour has list of cities - ("4","5","27","74")
AND second_tour has list of cities - ("1","5")
Let's assume i have two values - 4 and 74:
Now, i need to get all rows from first table, where my both values are in the list of cities. i.e it must return only the first_tour (because 4 and 74 are in it's list of cities)
So, i wrote the following query
SELECT t.name
FROM `incoming_tours` t
JOIN `incoming_tours_cities` tc0 ON tc0.id_parrent = t.id
AND tc0.id_city = '4'
JOIN `incoming_tours_cities` tc1 ON tc1.id_parrent = t.id
AND tc1.id_city = '74'
And that works fine.
But i generate the query dynamically, and when the count of joins is big (about 15) the query slowing down.
i.e. when i try to run
SELECT t.name
FROM `incoming_tours` t
JOIN `incoming_tours_cities` tc0 ON tc0.id_parrent = t.id
AND tc0.id_city = '4'
JOIN `incoming_tours_cities` tc1 ON tc1.id_parrent = t.id
AND tc1.id_city = '74'
.........................................................
JOIN `incoming_tours_cities` tc15 ON tc15.id_parrent = t.id
AND tc15.id_city = 'some_value'
the query run's in 45s(despite on i set indexes in the tables)
What can i do, to optimaze it?
Thanks much
SELECT t.name
FROM incoming_tours t INNER JOIN
( SELECT id_parrent
FROM incoming_tours_cities
WHERE id IN (4, 74)
GROUP BY id_parrent
HAVING count(id_city) = 2) resultset
ON resultset.id_parrent = t.id
But you need to change number of total cities count.
SELECT name
FROM (
SELECT DISTINCT(incoming_tours.name) AS name,
COUNT(incoming_tours_cities.id_city) AS c
FROM incoming_tours
JOIN incoming_tours_cities
ON incoming_tours.id=incoming_tours_cities.id_parrent
WHERE incoming_tours_cities.id_city IN(4,74)
HAVING c=2
) t1;
You will have to change c=2 to whatever the count of id_city you are searching is, but since you generate the query dynamically, that shouldn't be a problem.
I'm pretty sure this works, but a lot less sure that it is optimal.
SELECT * FROM incoming_tours
WHERE
id IN (SELECT id_parrent FROM incoming_tours_cities WHERE id_city=4)
AND id IN (SELECT id_parrent FROM incoming_tours_cities WHERE id_city=74)
...
AND id IN (SELECT id_parrent FROM incoming_tours_cities WHERE id_city=some_value)
Just an hint.
If you use the IN operator in a WHERE clause, you can hope that the short-circuit of operator AND may remove unnecessary JOINs during the execution for the tours that do not respect the constraint.
Seems like an odd way to do that query, here
SELECT t.name FROM `incoming_tours` as t WHERE t.id IN (SELECT id_parrent FROM `incoming_tours_cities` as tc WHERE tc.id_city IN ('4','74'));
I think that does it, but not tested...
EDIT: Added table alias to sub-query
I've written this query using CTE's and it includes the test data in the query. You'll need to modify it so that it queries the real tables instead. Not sure how it performs on a large dataset...
Declare #numCities int = 2
;with incoming_tours(id, name) AS
(
select 1, 'first_tour' union all
select 2, 'second_tour' union all
select 3, 'third_tour' union all
select 4, 'fourth_tour'
)
, incoming_tours_cities(id_parent, id_city) AS
(
select 1, 4 union all
select 1, 5 union all
select 1, 27 union all
select 1, 74 union all
select 2, 1 union all
select 2, 5
)
, cityIds(id_city) AS
(
select 4
union all select 5
/* Add all city ids you need to check in this table */
)
, common_cities(id_city, tour_id, tour_name) AS
(
select c.id_city, it.id, it.name
from cityIds C, Incoming_tours_cities tc, incoming_tours it
where C.id_city = tc.id_city
and tc.id_parent = it.id
)
, tours_with_all_cities(id_city) As
(
select tour_id from common_cities
group by tour_id
having COUNT(id_city) = #numCities
)
select it.name from incoming_tours it, tours_with_all_cities tic
where it.id = tic.id_city
Related
I have a table. Table has structure of id, name, color, product_id.
And the table has multiple rows with the same product_id.
With SQL query from PHP file - I would like to choose only one, the oldest, row. (The first one that was added to the current table).
What query should I use or approach?
Thank you!
Just making up a bit of mockup data ... Note the notes I put in. And I trust it's a newer version of MySQL, as the older ones did not support ROW_NUMBER() OVER() .
Here goes:
WITH
-- input ... you *need* a timestamp to identify the oldest ---
indata(id, name, color, product_id,ts) AS (
SELECT 1,'Arthur','blue' ,42,TIMESTAMP'2021-01-31 17:45:00'
UNION ALL SELECT 1,'Arthur','blue' ,42,TIMESTAMP'2021-01-31 17:50:00'
UNION ALL SELECT 1,'Arthur','blue' ,42,TIMESTAMP'2021-01-31 17:55:00'
UNION ALL SELECT 1,'Arthur','blue' ,42,TIMESTAMP'2021-01-31 18:00:00'
UNION ALL SELECT 2,'Ford' ,'red' ,42,TIMESTAMP'2021-01-31 17:45:00'
UNION ALL SELECT 2,'Ford' ,'blue', 42,TIMESTAMP'2021-01-31 17:50:00'
UNION ALL SELECT 2,'Ford' ,'green',42,TIMESTAMP'2021-01-31 17:55:00'
UNION ALL SELECT 2,'Ford' ,'cyan' ,42,TIMESTAMP'2021-01-31 18:00:00'
)
,
-- select all, plus a rank, on which you will filter outside ..
with_rank AS (
SELECT
*
, ROW_NUMBER() OVER(PARTITION BY id ORDER BY ts) AS rnk
FROM indata
)
SELECT
id
, name
, color
, product_id
, ts
FROM with_rank
WHERE rnk = 1
id|name |color|product_id|ts
1|Arthur|blue |42 |2021-01-31 17:45:00
2|Ford |red |42 |2021-01-31 17:45:00
One method is a correlated subquery:
select t.*
from t
where t.id = (select min(t2.id)
from t t2
where t2.product_id = t.product_id
);
This assumes that id is incrementing with each insertion. If not, you have no way of knowing what the "oldest" row is. SQL tables represent unordered sets, so there is no "oldest" row unless a column contains that information.
SELECT * FROM TableName WHERE product_id = ProductID ORDER BY product_id LIMIT 1;
Two tables, with a left join. For ease table 1 and table 2.
Table 1 contains a list of people and their current status, table 2 is all of their "invites". All im trying to do as part of the join is show in a list all the current "people" and then the LATEST invite status (from table 2) so return a single row from table 2.
I have everything working... but its duplicating for example if a person has had multiple invites it will put them twice on the list. I just want to limit it to
$sql = "SELECT table1.fieldname as table1fielname table2.fieldname [more fields]
FROM xxx
LEFT JOIN xxx on table1.sharedid=table2.sharedid
WHERE XXX LIMIT 1 ";`
Obvioulsy the limit 1 doesnt do what its supposed to. I have tried adding additional select statements in brackets but being honest it just breaks everything and im not an expert at all.
I'm not an expert too but I'll try. Have you tried to use DISTINCT?
For exemple:
SELECT DISTINCT column_name1,column_name2
FROM table_name; [...]
It normally delete double matches.
Here are the links:
http://www.w3schools.com/sql/sql_distinct.asp
https://www.techonthenet.com/oracle/distinct.php
Give example data. And use good table and column names. For example:
(this returns all rows that satisfy the join):
WITH people(ppl_id,ppl_name,status) AS (
SELECT 1,'Arthur','active'
UNION ALL SELECT 2,'Tricia','active'
), invites(ppl_id,inv_id,inv_date) AS (
SELECT 1,1, DATE '2017-01-01'
UNION ALL SELECT 1,2, DATE '2017-01-07'
UNION ALL SELECT 1,3, DATE '2017-01-08'
UNION ALL SELECT 2,1, DATE '2017-01-01'
UNION ALL SELECT 2,2, DATE '2017-01-08'
)
SELECT
*
FROM people
JOIN invites USING(ppl_id)
ORDER BY 1
;
ppl_id|ppl_name|status|inv_id|inv_date
1|Arthur |active| 1|2017-01-01
1|Arthur |active| 3|2017-01-08
1|Arthur |active| 2|2017-01-07
2|Tricia |active| 2|2017-01-08
2|Tricia |active| 1|2017-01-01
But we want only 'Arthur' with '2017-01-08' and 'Tricia' with '2017-01-08'.
With any database that supports ANSI 99, you could try with a temporary table containing the newest invitation date per "people id", and join that temporary table with the invitations table. We call that table newest_invite_date, and, apparently, it does what we expect it to do:
WITH people(ppl_id,ppl_name,status) AS (
SELECT 1,'Arthur','active'
UNION ALL SELECT 2,'Tricia','active'
), invites(ppl_id,inv_id,inv_date) AS (
SELECT 1,1, DATE '2017-01-01'
UNION ALL SELECT 1,2, DATE '2017-01-07'
UNION ALL SELECT 1,3, DATE '2017-01-08'
UNION ALL SELECT 2,1, DATE '2017-01-01'
UNION ALL SELECT 2,2, DATE '2017-01-08'
), newest_invite_date(ppl_id,inv_date) AS (
SELECT ppl_id,MAX(inv_date)
FROM invites
GROUP BY ppl_id
)
SELECT
people.ppl_id
, people.ppl_name
, people.status
, newest_invite_date.inv_date
FROM people
JOIN newest_invite_date USING(ppl_id)
ORDER BY 1
;
ppl_id|ppl_name|status|inv_date
1|Arthur |active|2017-01-08
2|Tricia |active|2017-01-08
Is this what you were looking for?
Happy playing ...
Marco the Sane
I am running this query, and I am getting ** #1241 - Operand should contain 1 column(s)** error:
SELECT `forumCategories`.`id`, `forumCategories`.`name`, `forumCategories`.`order`, `forumCategories`.`description`, `forumCategories`.`date_created`, COUNT(forumPosts.forumCategory_id) as postCount,
(SELECT `forumPosts`.*, `forumChildPosts`.`id`, `forumChildPosts`.`forumPost_id`, COUNT(forumChildPosts.forumPost_id) as childCount FROM `forumChildPosts` LEFT JOIN `forumPosts` ON `forumPosts`.`id` = `forumChildPosts`.`forumPost_id` GROUP BY `forumPosts`.`id`) AS childCount
FROM `forumCategories`
LEFT JOIN `forumPosts` ON `forumCategories`.`id` = `forumPosts`.`forumCategory_id`
GROUP BY `forumCategories`.`id`
ORDER BY `forumCategories`.`order` DESC
I have 3 tables:
forumCategories
forumPosts | forumPosts.forumCategory_id = forumCategories.id
forumChildPosts | forumChildPosts.forumPosts_id = forumPosts.id
I want to count all posts for the forum category, and them I want to count all the child posts that belongs to that forum category. How can I do this?
You can't select several items with a subselect and then give them one name. Now you're getting everything from forumPosts, something from forumChildPosts etc and trying to put that into a single column, childCount. This is not allowed.
It might be enough to remove all other result columns from that select and only leave the count?
I couldn't try it, is that makes sense ? But you can't get nested results from mysql due to its limitation, MYSQL is a Matrix table.
SELECT `forumCategories`.`id`,
`forumCategories`.`name`,
`forumCategories`.`order`,
`forumCategories`.`description`,
`forumCategories`.`date_created`,
COUNT(forumPosts.forumCategory_id) AS postCount,
(SELECT COUNT(forumChildPosts.forumPost_id) AS childCount FROM `forumChildPosts` LEFT JOIN `forumPosts` ON `forumPosts`.`id` = `forumChildPosts`.`forumPost_id` GROUP BY `forumPosts`.`id`) AS childCount
FROM `forumCategories`
LEFT JOIN `forumPosts` ON `forumCategories`.`id` = `forumPosts`.`forumCategory_id`
GROUP BY `forumCategories`.`id`
ORDER BY `forumCategories`.`order` DESC
I have a small list of data which is from an SQL database and uses mysql_fetch_array($query_run) to get it. This all works fine and I can echo out that data to double check it.
But where I want to use it is another SQL query, but where it doesn't equal it. My code at the moment only doesn't include one of the data items. So, I'm guessing you have to do something to let it know it's an array not just one piece of data?
Here's my code:
$query = "SELECT * FROM myFriends WHERE idPerson = '$loggedInUserId'";
$query_run = mysql_query($query);
while($row = mysql_fetch_array($query_run)) {
$idfriend = $row['idFriend'];
$queryFrirend = "SELECT * FROM perosn WHERE idPerson != '$idfriend'
Any help would be great!
Personally, I wouldn't bother with turning an array into a WHERE clause, if the set is returned from a MySQL query. Relational databases are built for this kind of thing.
A query with the familiar anti-join pattern will return the specified result:
SELECT p.*
FROM person p
LEFT
JOIN myFriends f
ON f.idFriend = p.idPerson
AND f.idPerson = '$loggedInUserId'
WHERE f.idFriend IS NULL
This says get all rows from the person table, and match to rows from the myFriends table. The WHERE clause says to exclude rows where a matching row was found, leaving only rows from person that didn't have a matching row returned from myFriends. With appropriate indexes, MySQL can blaze through that, without the overhead of sending a list of id values in a WHERE clause.
But, that doesn't really answer the question you asked.
The SQL you specified, including a list of idPerson values to be excluded, can be of several forms:
SELECT p.*
FROM person p
WHERE p.idPerson NOT IN (2,3,5,7,11,13,15,17,19)
or
SELECT p.*
FROM person p
WHERE p.idPerson <> 2
AND p.idPerson <> 3
AND p.idPerson <> 5
AND p.idPerson <> 7
AND p.idPerson <> 11
AND p.idPerson <> 13
AND p.idPerson <> 15
AND p.idPerson <> 17
or
SELECT p.*
FROM person p
WHERE NOT EXISTS
( SELECT 1
FROM ( SELECT 2 AS idPerson
UNION ALL SELECT 3
UNION ALL SELECT 5
UNION ALL SELECT 7
UNION ALL SELECT 9
UNION ALL SELECT 11
UNION ALL SELECT 13
UNION ALL SELECT 15
UNION ALL SELECT 17
UNION ALL SELECT 19
) f
WHERE f.idPerson = p.idPerson
)
or
SELECT p.*
FROM person p
LEFT
JOIN ( SELECT 2 AS idPerson
UNION ALL SELECT 3
UNION ALL SELECT 5
UNION ALL SELECT 7
UNION ALL SELECT 9
UNION ALL SELECT 11
UNION ALL SELECT 13
UNION ALL SELECT 15
UNION ALL SELECT 17
UNION ALL SELECT 19
) f
ON f.idPerson = p.idPerson
WHERE f.idPerson IS NULL
It's just a matter of looping through the rows in the result set, and using that value to format an appropriate SQL statement. The easiest approach (apart from aforementioned avoidance of having to run two separate queries to get the resultset you want), would be to build an array of the friendId column values. And then turn that array into a string of comma separated literals 2,3,5,7,9,11,13,17,19. Of course, you'd need to handle the edge case of no rows returned, because foo NOT IN () isn't valid SQL syntax.
If you want to build the statement on the fly, as you loop through the rows, you could do something like this:
$queryFrirend = "SELECT * FROM person WHERE 1=1";
while($row = mysql_fetch_array($query_run)) {
$queryFrirend .= " AND idPerson <> " . (int) $row['idFriend'];
}
$queryFrirend .= " ORDER BY idPerson";
echo "SQL=", $queryFrirend;
Though that's going to some ugly SQL. (I don't want to be around when the DBA comes hunting for you.)
You can't use arrays in SQL queries. You need to turn the array into a String of values separated by commas, and use IN().
SELECT * FROM perosn WHERE idPerson Not IN ('person1', 'person2')
How can I merge the following queries together?
To get all the objects of a particular type I use
SELECT ID FROM social_objects
WHERE subgroup='23' ORDER BY time_created DESC LIMIT 0 , 30
I have this search too, for titles
SELECT ID FROM 'social_objects_single'
WHERE 'title' LIKE '%indian%' LIMIT 0 , 30
How can I get only objects of subgroup 23 with certain titles?
How are the two tables related? If they both reference an ID you inner join and use AND to combine conditions:
SELECT Parent.ID, Child.ID
FROM ParentTable
INNER JOIN ChildTable ON ParentTable.ID = ChildTable.ForeignKeyID
WHERE Parent.ID = 23 AND Title LIKE '%indian%'
If your social_objects_single has the same ID as the social_objects table you could do this:
SELECT so.ID FROM social_objects so
INNER JOIN social_objects_single soi ON soi.ID = so.ID
WHERE so.subgroup = 23 AND soi.title LIKE '%indian%'
ORDER BY so.time_created DESC LIMIT 0, 30;
SELECT SO.ID,SOS.ID
FROM social_objects SO ,social_objects_single SOS WHERE SOS.title LIKE '%indian% and SO.subgroup=23 and SOS.id =SO.subgroup_id
you should replace the last condition SOS.id =SO.subgroup_id as your tables are connected