SQL select with multiple conditions on the same table - mysql

I have 2 tables in MySQL, the first one has 2 columns: ID and name, the second has 3 columns: firstTableId (foreign key on the first table), key, value.
I have the following rows in table 1:
1,Bob
2,Alice
3,Fred
I have the following rows in table 2:
1,age,20
1,gender,male
2,age,20
2,gender,female
3,age,18
3,gender,male
I would like to write a select query using only the last 2 columns on the second table (key and value) that returns only Bob form the first table, but I can't seem to figure it out.
Essentially I want to select from the first table all rows where, in the second table, we have key=age and value=20 for one row, and key=gender and value=male in another row. Can anyone point me in the right direction ? Manipulating table structure is not preferred as this is a simplified example and both "key" and "value" columns in the second table can be pretty much anything, it's not actually limited to "age" and "gender".
Thanks in advance.

You can do this with a self join like this:
select
*
from
table1 t1
inner join table2 age on t1.id = age.id
inner join table2 gender on t1.id = gender.id
where
(age.`key` = 'age' and age.value = 20)
and
(gender.`key` = 'gender' and gender.value = 'male')
An additional tactic you may want to try is a PIVOT query. Mysql doesnt have anything native to support pivot's, but there are several examples of how to do them.
You can see it working in this fiddle

Use two IN clauses (or two EXISTS clauses).
select *
from table1
where id in (select firstTableId from table2 where key = 'age' and value = '20')
and id in (select firstTableId from table2 where key = 'gender' and value = 'male');
With EXISTS:
select *
from table1
where exists (select * from table2 where key = 'age' and value = '20' and firstTableId = table1.firstTableId)
and exists (select * from table2 where key = 'gender' and value = 'male' and firstTableId = table1.firstTableId);

Related

Selecting a Group of records based on a single Record Value

Let us consider we I have a table as follows
I need to select the records with same "group_id" s where at least anyone record's "type" is equal to 1.
The expected result set must be like
This should work:
select * from table where group_id in
(
select group_id from table where type = 1
)
You can also try join instead of in
select a.* from table a
join
(
select group_id from table where type = 1
) b on b.group_id = a.group_id

SQL OR Operator on different tables and column names

I know that I can use the OR SQL operator on the same column of a table like the following:
SELECT * FROM users WHERE last_name = 'Peter' OR last_name = 'Smith';
But the situation I have right now is that I'm trying to use the OR operator on two different tables (different column names). Is that possible? How can I achieve that in an SQL query?
And yes there is a foreign key column that links one table to the primary key column of the other table.
Thanks in advance for any help.
If the fields in the different tables have the same name, you can distinguish them with tablename.fieldname, if the tables have the same name (in different schemas), you can further qualify the names with schemaname.tablename.fieldname.
Of course, all tables referenced in the WHERE and SELECT clauses should be included in the FROM clause.
Note: If a table is aliased in the FROM, the alias should be used instead of the table name.
You cannot display (or use in WHERE conditions, etc...) fields from a table that not included in the FROM; however, you can use subqueries on those tables.
Examples:
...
FROM table1 AS t1
WHERE t1.field1 = somevalue
OR EXISTS (
SELECT *
FROM table2 AS t2
WHERE t2.somefield = someothervalue
)
...
or
SELECT t1.field1
, (SELECT t2.somefield FROM table2 AS t2 WHERE t2.anotherfield = somevalue LIMIT 1) AS t2Val
FROM table1 AS t1
...
Yes , it is possible
SELECT users.* FROM users,countries WHERE users.last_name = 'Peter' OR countries.name = 'mexico' AND users.idCountry=countries.id;

SQL Join 2 tables with almost same field

I need to join two tables in SQL. There are no common fields. But the one table have a field with the value krin1001 and I need it to be joined with the row in the other table where the value is 1001.
The idea behind the joining is i have multiple customers, but in the one table there customer id is 'krin1001' 'krin1002' and so on, in this table is how much they have sold. In the other table there customer is is '1001' '1002' and so on, and in this table is there name and adress and so on. So it will always be the first 4 charakters i need to strip from the field before matching and joining. It might not always be 'krin' i need it to work with 'khjo1001' also, and it still needs to join on the '1001' value from the other table.
Is that possible?
Hope you can help me.
You need to use substring:
ON SUBSTRING(TableA.Field, 5, 4) = TableB.Field
Or Right:
ON RIGHT(TableA.Field, 4) = TableB.Field
You can also try to use CHARINDEX function for join operation. If value from table1 contains value from table2 row will be included in result set.
;WITH table1 AS(
SELECT 'krin1001' AS val
UNION ALL
SELECT 'xxx'
UNION ALL
SELECT 'xyz123'
),
table2 AS(
SELECT '1001' AS val
UNION ALL
SELECT '12345'
UNION ALL
SELECT '123'
)
SELECT * FROM table1 AS t
JOIN table2 AS T2 ON CHARINDEX(T2.val, T.val) > 0
Use it as:
SELECT
*
FROM table t1
INNER JOIN table t2 ON RIGHT(t1.col1, 4) = t2.col1;

How to write a SQL join to retrieve results from second table?

Table 1: id#, name, color
Table 2: id#
I would like to get all the results from Table 1 WHERE color = "green". After finding the subset of color 'green' from table 1, I then want to find all the matching id#'s from Table 2.
Essentially getting the set from Table 1 with a color=green that exist in Table 2.
Thanks for help with this query!
SELECT * FROM TABLE2
WHERE ID IN (SELECT ID FROM TABLE1 WHERE color = 'green');
Is this what you want?
SELECT *
FROM Table1 t1
JOIN Table2 t2 ON t1.Table2_ID = t2.ID
WHERE t1.Colour = 'Green'
Edit: Just noticed you've updated the question with the column names. I'll let you do the substitution ;)

Mysql SELECT narrowing search

EDIT:That was fast. The reason why I have this is because the table is a pivot table between 2 tables one has "id" as primary key and the other "type" primary key
Hello.
I want the following:
Find only find "id" where "type" is 1 AND 2 AND 3
This is not working:
SELECT * FROM `table` WHERE `type` = 1 AND `type` = 2 AND `type` = 3;
The SELECT statment should only return one row (id = 1)
Table
id type
1 1
1 2
1 3
2 1
2 2
3 3
If you only want to know the Id then add the keyword Distinct and just select the id,
where there are records for the three different types ...
Select Distinct id
FROM `table` t
WHERE Exists (Select * From Table Where id = t.id and Type = '1')
And Exists (Select * From Table Where id = t.id and Type = '2')
And Exists (Select * From Table Where id = t.id and Type = '3')
If you want to see the Id and the type then add the type to the select,
Select Distinct id, Type
FROM `table` t
WHERE Exists (Select * From Table Where id = t.id and Type = '1')
And Exists (Select * From Table Where id = t.id and Type = '2')
And Exists (Select * From Table Where id = t.id and Type = '3')
if you want to see every row that has that id, then leave out the distinct
Select id, Type
FROM `table` t
WHERE Exists (Select * From Table Where id = t.id and Type = '1')
And Exists (Select * From Table Where id = t.id and Type = '2')
And Exists (Select * From Table Where id = t.id and Type = '3')
A row can't have a column with a value 1 AND 2 AND 3 at the same time. It's like asking you if you're "20 and 21 and 22 years old". You can only be one of them.
You'd want to do something akin to:
SELECT id WHERE type = 1
INTERSECT
SELECT id WHERE type = 2
INTERSECT
SELECT id WHERE type = 3
but MySQL doesn't support INTERSECT, so you have to do it by hand:
SELECT id FROM table WHERE
id IN (SELECT id FROM table WHERE
id IN (SELECT id FROM table WHERE type = 3)
AND type = 2)
AND type = 1
You can do it using intersection of sets
SELECT id FROM table WHERE type = 1
INTERSECT
SELECT id FROM table WHERE type = 2
INTERSECT
SELECT id FROM table WHERE type = 3
I am thinking if there is also simplier query but now I have no idea
Your search conditions are incompatible. Field 'type' can't be at the same time equal to 1, 2 and 3. Given the absence of INTERSECT in MySQL, you can join the same table two times:
SELECT id FROM
Table t1 JOIN Table t2 ON (t1.id=t2.id) JOIN Table t3 ON (t3.id=t2.id)
WHERE t1.type=1 AND t2.type=2 AND t3.type=3
This will build a cartesian product of rows with the same id and retain only those which have all three types you want.
Learning the basics of SQL can help you a lot. There is a lot of information around. (including MySQL docs)
If I understand you correctly, couldn't you just add LIMIT 1 at the end of your query?
Your selecting for the impossible. For each row, type can not be three things at once.
You're doing something wrong. You should not have multiple rows with the same id. It destroys the point of having one. Your id column should be a primary key that auto increments.
I think you should go back and reexamine your schema. Or at least add more detail about what you're trying to do.