Select multiple rows with multiple matching id(s) - mysql

Is there a way to query data to display multiple rows with multiple selector?
like:
SELECT * FROM `book` WHERE `book`.id = 1 AND `book`.id = 2;
table:
id name
1 book1
2 book2
3 book3
4 book4
I dun suppose looping for each id is favourable.

Well, yeah, you can use in, but this is the same as multiple or, not and – one value can't be equal to the two unequal values at once:
select *
from `book`
where `book`.id in(1, 2)

One solution you have, but you made an error. An id cannot be both 1 and 2, so you need to use OR to return those rows that are either 1 or 2.
SELECT * FROM `book` WHERE `book`.id = 1 OR `book`.id = 2;
A slightly simpler notation would be:
SELECT * FROM `book` WHERE `book`.id in (1, 2);

Related

Find single entries where there should be 2

I am looking to find all the single entries in a table where there should only be double entries.
Eg.
Unique_Key
ID
State_Sequence_ID
Localisation_Format_ID
File_Name
6644106
1315865
100
1
2064430-DNK.pac
6644107
1315865
190
2
2064430.chk [DNK]
I am looking to find all instances where the 2nd record does not exist.
The ID for each record will always be the same (although I do not know what that ID will be specifically) and the Localisation Format ID will always be 1 and 2. I am looking to find all entries where Localisation Format ID 2 does not exist.
SELECT *
WHERE ID has Localisation_Format_ID = 1
but does not have Localisation_Format_ID = 2
This is a simple not exists criteria:
select *
from t
where not exists (
select * from t t2 where t2.Id = t.Id and t2.Localisation_Format_ID = 2
);

How to treat missing id 's value as 0 and order by it?

When I use in keyword in sql, there may be some id is missing , but I want treat them like they exist and other columns are null or 0.
For example, suppose I have a table with two columns and some rows:
[id,value1]
1      1
2      4
3      3
5      5
I may write sql like this:
select * from table where id in (1,4,5) order by value1 limit 0,2 ;
When this sql is executed, the return result is [(1,1),(5,5)].
But what I want is [(4,0),(1,1)], because I want to treat the missing id 4 like it exists in the table.
So the question is : Is there some elegant way to achieve it using sql instead of select all rows and sort them in memory.
Use a left join:
select *
from (select 1 as id union all
select 4 union all
select 5
) i left join
table t
using (id)
order by t.value1
limit 0, 2 ;
Note that you are ordering by a value in the existing table, so this depends on the fact that NULL is ordered before other values.

Combine database queries

I have a MySQL table that looks like this:
ID / x_id / x_key / x_value
322 / 4 / name / Jack
323 / 5 / name / Mary
324 / 6 / name / John
325 / 4 / hide / 1
326 / 5 / hide / 0
327 / 6 / hide / 0
I would like to select the names from the persons which "hide" key corresponds to the "0" value.
Here these selected "x_values" would then be Mary and John
To do so, I have the x_id that I can compare between records.
Which x_id's correspond to an x_ key="hide" that matches an x_value = "0"?
Both x_id's 5 and 6.
Which "x_values" are corresponding to these two x_id's where the x_key="name"? Mary and John
In other words, I try to get a single query that would mix these two queries in order to get Mary and John only:
Query A:
SELECT
x_id,
x_value
FROM
mytable
WHERE
x_key='name'
Query B:
SELECT
x_id
FROM
mytable
WHERE
x_key='hide'
AND
x_value='0'
I just don't find the correct way to do that.
How can I?
I'm really sorry for the explanation but I'm not english and it is very hard to explain.
If i have understood you correct you want to select the elements that have a specific x_key with x_value = '0' and that are not hidden (x_key != 'hide').
EDIT (according to your edit):
SQL Fiddle
SELECT bb.x_value
FROM mytable AS aa
INNER JOIN mytable AS bb
ON aa.x_id = bb.x_id
WHERE aa.x_key = 'hide' AND aa.x_value = 0 AND bb.x_key = 'name';
OLD ANSWER (before your edit):
SELECT x_id, x_key, x_value
FROM mytable
WHERE x_key='name' AND x_key != 'hide' AND x_value = '0'
You should use join to connect two instances of the table - one for the names and one for the 'hides'
select n.x_id, n.x_value from mytable as h inner join myable as n on
h.x_id = n.x_id where n.x_key = 'name' and h.x_key = 'hide' and H.x_value = 0;
while this will work, I think it's not a good practice to have two types of data in the same table. I'd recommend you to split it to two tables- one for names and one for hides
If I understand you correct you want combine 2 'SELECT' with different 'WHERE' statments. You can use 'OR' statment
SELECT x_id,x_value FROM mytable WHERE x_key='name' OR x_key='hide' AND x_value='0'

Mysql Dynamic crosstab Pivot comparison on one table

I have a many to many table setup. This is an example of table I am focusing on.
many_to_many_id, foreign_key_id
1, 1
1, 2
1, 3
2, 1
2, 2
3, 1
3, 4
I need to given many_to_many_id 1 find any other many_to_many_ids that have matching foreign keys that exist within the first set. Given the first set 1, 2, 3 attached to many_to_many_id would return 2 as 1, and 2 are inside the set, but 3 would not be returned as 4 is not part of the test set. My boss has said I should use a dynamic cross tab to create two tables to compare with a join. I have looked for examples but they have not been helpful.
You can do this with a few simple sub-queries. The first will make sure that for each many_to_many_id there is at least one foreign_key_id in the set you're looking for (1, 2, 3) and the second will make sure there isn't even one foreign_key_id not in the set you're looking for.
SET #search_id = 1;
SELECT m.many_to_many_id FROM SampleTable m
WHERE m.many_to_many_id != #search_id
AND EXISTS ( SELECT 1 FROM SampleTable a WHERE a.many_to_many_id = m.many_to_many_id AND a.foreign_key_id IN ( SELECT b.foreign_key_id FROM SampleTable b WHERE b.many_to_many_id = #search_id ) )
AND NOT EXISTS ( SELECT 1 FROM SampleTable a WHERE a.many_to_many_id = m.many_to_many_id AND a.foreign_key_id NOT IN ( SELECT b.foreign_key_id FROM SampleTable b WHERE b.many_to_many_id = #search_id ) )
GROUP BY m.many_to_many_id
SQL Fiddle Here

mysql distribution of combinations/values

I have a mysql table which contains some random combination of numbers. For simplicity take the following table as example:
index|n1|n2|n3
1 1 2 3
2 4 10 32
3 3 10 4
4 35 1 2
5 27 1 3
etc
What I want to find out is the number of times a combination has occured in the table. For instance, how many times has the combination of 4 10 or 1 2 or 1 2 3 or 3 10 4 etc occured.
Do I have to create another table that contains all possible combinations and do comparison from there or is there another way to do this?
For a single combination, this is easy:
SELECT COUNT(*)
FROM my_table
WHERE n1 = 3 AND n2 = 10 AND n3 = 4
If you want to do this with multiple combinations, you could create a (temporary) table of them and join that table with you data, something like this:
CREATE TEMPORARY TABLE combinations (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
n1 INTEGER, n2 INTEGER, n3 INTEGER
);
INSERT INTO combinations (n1, n2, n3) VALUES
(1, 2, NULL), (4, 10, NULL), (1, 2, 3), (3, 10, 4);
SELECT c.n1, c.n2, c.n3, COUNT(t.id) AS num
FROM combinations AS c
LEFT JOIN my_table AS t
ON (c.n1 = t.n1 OR c.n1 IS NULL)
AND (c.n2 = t.n2 OR c.n2 IS NULL)
AND (c.n3 = t.n3 OR c.n3 IS NULL)
GROUP BY c.id;
(demo on SQLize)
Note that this query as written is not very efficient due to the OR c.n? IS NULL clauses, which MySQL isn't smart enough to optimize. If all your combinations contain the same number of terms, you can leave those out, which will allow the query to make use of indexes on the data table.
Ps. With the query above, the combination (1, 2, NULL) won't match (35, 1, 2). However, (NULL, 1, 2) will, so, if you want both, a simple workaround would be to just include both patterns in your table of combinations.
If you actually have many more columns than shown in your example, and you want to match patterns that occur in any set of consecutive columns, then your really should pack your columns into a string and use a LIKE or REGEXP query. For example, if you concatenate all your data columns into a comma-separated string in a column named data, you could search it like this:
INSERT INTO combinations (pattern) VALUES
('1,2'), ('4,10'), ('1,2,3'), ('3,10,4'), ('7,8,9');
SELECT c.pattern, COUNT(t.id) AS num
FROM combinations AS c
LEFT JOIN my_table AS t
ON CONCAT(',', t.data, ',') LIKE CONCAT('%,', c.pattern, ',%')
GROUP BY c.id;
(demo on SQLize)
You could make this query somewhat faster by making the prefixes and suffixes added with CONCAT() part of the actual data in the tables, but this is still going to be a fairly inefficient query if you have a lot of data to search, because it cannot make use of indexes. If you need to do this kind of substring searching on large datasets efficiently, you may want to use something better suited for than specific purpose than MySQL.
You only have three columns in the table, so you are looking for combinations of 1, 2, and 3 elements.
For simplicity, I'll start with the following table:
select index, n1 as n from t union all
select index, n2 from t union all
select index, n3 from t union all
select distinct index, -1 from t union all
select distinct index, -2 from t
Let's call this "values". Now, we want to get all triples from this table for a given index. In this case, -1 and -2 represent NULL.
select (case when v1.n < 0 then NULL else v1.n end) as n1,
(case when v2.n < 0 then NULL else v2.n end) as n2,
(case when v3.n < 0 then NULL else v3.n end) as n3,
count(*) as NumOccurrences
from values v1 join
values v2
on v1.n < v2.n and v1.index = v2.index join
values v3
on v2.n < v3.n and v2.index = v3.index
This is using the join mechanism to generate the combinations.
This method finds all combinations regardless of ordering (so 1, 2, 3 is the same as 2, 3, 1). Also, this ignores duplicates, so it cannot find (1, 2, 2) if 2 is repeated twice.
SELECT
CONCAT(CAST(n1 AS VARCHAR(10)),'|',CAST(n2 AS VARCHAR(10)),'|',CAST(n3 AS VARCHAR(10))) AS Combination,
COUNT(CONCAT(CAST(n1 AS VARCHAR(10)),'|',CAST(n2 AS VARCHAR(10)),'|',CAST(n3 AS VARCHAR(10)))) AS Occurrences
FROM
MyTable
GROUP BY
CONCAT(CAST(n1 AS VARCHAR(10)),'|',CAST(n2 AS VARCHAR(10)),'|',CAST(n3 AS VARCHAR(10)))
This creates a single column that represents the combination of the values within the 3 columns by concatenating the values. It will count the occurrences of each.