The title is a bit wrong, i can explain better here.
Say i have a MySQL table like this:
mysql> select * from people;
+------+---------------+
| name | number |
+------+---------------+
| John | 100000 |
| Alex | 200000 |
| Tim | 500000 |
| Alice| 100000 |
| Peter| 500000 |
+------+---------------+
And now i want a query which returns the names of the people who have the same number, ie, for this table i would a query which would return John and Alice (they have the same number, 100000) and Tim and Peter (the same number 500000)
Try self join as below:
SELECT p1.name
FROM people p1 INNER JOIN people p2
ON p1.number = p2.number
WHERE p1.name != p2.name
You can do this by aggregating on the number column and using group_concat(). A having clause selects only cases where there is more than one name:
select number, group_concat(name) as names
from table t
group by number
having count(*) > 1;
Related
I have the following table:
Name Product
Bob Car
Bob Apples
Bob Pears
Bob Car
John Apples
John Pears
Whoever has bought a Product Car, I want to keep separate from everyone else. So, I create a flag:
Name Product Flag
Bob Car 1
Bob Apples 0
Bob Pears 0
Bob Car 1
John Apples 0
John Pears 0
But the problem with my flag is that even if I do a where condition and say, show me the consumer WHERE flag !=1, it'll pick Bob. Which is incorrect as Bob owns a car.
I would still like to GROUP by Product.
How do I separate the above table into two groups?
Thanks!
Use below query :-
select name from table where flag!=1
and name not in (select name from table where flag = 1)
group by name
"show me the consumer WHERE flag !=1, it'll pick Bob" that is because you are asking for rows where flag != 1. Instead you'll need something a little more complicated, like:
SELECT DISTINCT Name
FROM tableTable
WHERE Name NOT IN (SELECT Name FROM theTable WHERE Product = 'Car')
alternatively, you can do a LEFT JOIN, which may or may not be faster depending on the amount of data you have and how its values are distributed.
SELECT DISTINCT a.Name
FROM theTable a
LEFT JOIN theTable b ON a.Name = b.Name AND b.Product = 'Car'
WHERE a.Product != 'Car' AND b.Product IS NULL
;
This gets all the rows with products other than cars, and then uses the LEFT JOIN in conjunction with the IS NULL condition to find which did not also have a 'Car' row.
I think you want your table's data displayed, just with "People who bought cars" partitioned (not grouped) separately somehow - this could be done with an ORDER BY OwnsACar clause, for example.
Step 1: Identify the people who have bought cars:
SELECT DISTINCT
Name
FROM
yourTable
WHERE
Product = 'Car'
Step 2: Join on this data to generate a calculated "OwnsACar" column:
SELECT
yourTable.Name,
yourTable.Product,
ISNULL( carowners.Name ) AS OwnsACar
FROM
yourTable
LEFT OUTER JOIN
(
SELECT DISTINCT
Name
FROM
yourTable
WHERE
Product = 'Car'
) AS carowners ON carowners.Name = yourTable.Name
ORDER BY
OwnsACar ASC,
yourTable.Name ASC
You can use these two queries. The additional Flag column is not required.
-- do not have Car
SELECT *
FROM products
WHERE Name not in (SELECT DISTINCT Name
FROM products
WHERE Product='Car');
-- have Car
SELECT *
FROM products
WHERE Name in (SELECT DISTINCT Name
FROM products
WHERE Product='Car');
Illustration:
-- table
SELECT * FROM products;
+------+---------+
| Name | Product |
+------+---------+
| Bob | Car |
| Bob | Apples |
| Bob | Pears |
| Bob | Car |
| John | Apples |
| John | Pears |
+------+---------+
-- query for people that do not have Car
+------+---------+
| Name | Product |
+------+---------+
| John | Apples |
| John | Pears |
+------+---------+
-- query for people having 'Car'
+------+---------+
| Name | Product |
+------+---------+
| Bob | Car |
| Bob | Apples |
| Bob | Pears |
| Bob | Car |
+------+---------+
Try with :
SELECT `t`.`Name`, `t`.`Product`, SUM(`t`.`Flag`) as hasCar
FROM your_table t
GROUP BY `t`.`Name`
HAVING `t`.`hasCar` = 0;
Although you can go without the flag column by going :
SELECT `t`.`Name`, `t`.`Product`, SUM(IF(`t`.`Product` = 'Car', 1, 0)) as hasCar
FROM your_table t
GROUP BY `t`.`Name`
HAVING `t`.`hasCar` = 0;
This SQL tells me how much when the maximum occurred in the last hour, and is easily modified to show the same for the minimum.
SELECT
mt.mB as Hr_mB_Max,
mt.UTC as Hr_mB_Max_when
FROM
thundersense mt
WHERE
mt.mB =(
SELECT
MAX(mB)
FROM
thundersense mt2
WHERE
mt2.UTC >(UNIX_TIMESTAMP() -3600))
ORDER BY
utc
DESC
LIMIT 1
How do I modify it so it returns both maximum & minimum and their respective times?
Yours Simon M.
Based on my understanding of your question, you are looking to create a 4 column and 1 row answer where it looks like:
+-------+-----------------+----------+-----------------+
| event | time_it_occured | event | time_it_occured |
+-------+-----------------+----------+-----------------+
| fun | 90000 | homework | 12000 |
+-------+-----------------+----------+-----------------+
Below is a similar situation/queries you can adapt for your situation.
So, given a table called 'people' that looks like:
+----+------+--------+
| ID | name | salary |
+----+------+--------+
| 1 | bob | 40000 |
| 2 | cat | 12000 |
| 3 | dude | 50000 |
+----+------+--------+
You can use this query:
SELECT * FROM
(SELECT name, salary FROM people WHERE salary = (SELECT MAX(salary) FROM people)) t JOIN
(SELECT name, salary FROM people WHERE salary = (SELECT MIN(salary) FROM people)) a;
to generate:
+------+--------+------+--------+
| name | salary | name | salary |
+------+--------+------+--------+
| bob | 40000 | cat | 12000 |
+------+--------+------+--------+
Some things to note:
you can change the WHERE clauses to be the ones you have mentioned in question (for MAX and MIN).
Please be careful with the above query, here I am using a cartesian join (cross join in MYSQL) in order to get the 4 columns. To be honest, it doesn't make sense for me to get back data in one row but you said that's what you're looking for.
Here is what I would work with instead, getting two tuples/rows back:
+----------+--------+
| name | salary |
+----------+--------+
| dude | 95000 |
| Cat | 12000 |
+----------+--------+
And to generate this, you would use:
(SELECT name, salary FROM instructor WHERE salary = (SELECT MAX(salary) FROM instructor))
UNION
(SELECT name, salary FROM instructor WHERE salary = (SELECT MIN(salary) FROM instructor));
Also: A JOIN without a ON clause is just a CROSS JOIN.
How to use mysql JOIN without ON condition?
One method uses a join:
SELECT mt.mB as Hr_mB_Max, mt.UTC as Hr_mB_Max_when
FROM thundersense mt JOIN
(SELECT MAX(mB) as max_mb, MIN(mb) as min_mb
FROM thundersense mt2
WHERE mt2.UTC >(UNIX_TIMESTAMP() - 3600)
) mm
ON mt.mB IN (mm.max_mb, mm.min_mb)
ORDER BY utc DESC;
My only concern is your limit 1. Presumably, the mBs should be unique. If not, there is a bit of a challenge. One possibility would be to use an auto-incremented id rather than mB.
I need some help with counting both unique and duplicate values in MySQL. I want to know how many records there are total, and also how many is there two times and three times and so on...
Do I need to use UNION or something? I think SUM would be the best solution for me because of I might use some joins with this in future.
Sample data:
| custId | name |
|--------|--------|
| 1001 | Alex |
| 1001 | Alex |
| 1002 | Daniel |
| 1003 | Mark |
| 1002 | Daniel |
Sample results:
| total | twoTimes | threeTimes |
|-------|----------|------------|
| 3 | 2 | 0 |
Thanks in advance.
Just a basic group by should do it
SELECT YourValue, Count(YourValue)
FROM YourTable
GROUP BY YourValue
If you want only a category, like unique values ADD
HAVING Count(YourValue) = 1
Here is my approach:
http://sqlfiddle.com/#!9/9411dc/3
SELECT c.cnt AS `times`, COUNT(c.name) cnt
FROM (SELECT name, COUNT(custId) cnt
FROM cust
GROUP BY name) c
GROUP BY c.cnt;
that is not exactly what you did ask (you asked for pivot table which is very difficult to realize). So if you want to make it pivot you can read here: MySQL pivot table
And if you are sure that you have very small max of duplicate count your pivot query could be:
http://sqlfiddle.com/#!9/9411dc/5
SELECT
SUM(IF(c.cnt=1,1,0)) AS `Unique`,
SUM(IF(c.cnt=2,1,0)) AS `Two times`,
SUM(IF(c.cnt=3,1,0)) AS `Three times`,
SUM(IF(c.cnt=4,1,0)) AS `Four times`
FROM (SELECT name, COUNT(custId) cnt
FROM cust
GROUP BY name) c
I have 3 tables song, author, song_author.
Connection is song 1--* song_author 1--* author
I use a query like
SELECT *
FROM song
LEFT JOIN song_author ON s_id = sa_song
LEFT JOIN author ON sa_author = a_id
For the given example that would result in 3 rows:
John - How beautiful it is
John - Awesome
George - Awesome
and I am populating my objects like that so it's fine.
However, I want to add a LIMIT clause, but because it is returning several rows for just one song a LIMIT 10 doesn't always show 10 songs.
The other possibility I know is print all songs and then inside take a second query, but that would result in O(n) which I'd like to avoid.
author:
+------+--------+
| a_id | a_name |
+------+--------+
| 1 | John |
| 2 | George |
+------+--------+
song:
+------+---------------------+
| s_id | s_name |
+------+---------------------+
| 1 | How beautiful it is |
| 2 | Awesome |
+------+---------------------+
song_author:
+-----------+---------+
| sa_author | sa_song |
+-----------+---------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+-----------+---------+
You can try something like that:
SELECT *
FROM
(SELECT *
FROM song
LIMIT 10) r
LEFT JOIN song_author ON r.s_id = sa_song
LEFT JOIN author ON sa_author = a_id
To be clear, your goal is what, exactly? It seems like you want to grab a set amount of songs at one time (10 in the example), and all related authors for said songs. However, if multiple of those [song, author] record tuples represented the same song, you'd end up with 10 records, but less than 10 actual songs.
I like Marcin's approach, but if you want to avoid sub-queries and temporary tables, you can instead use a feature built into MySQL: GROUP_CONCAT()
SELECT
s_name,
GROUP_CONCAT(DISTINCT a_name SEPARATOR '|')
FROM
song
LEFT JOIN
song_author ON sa_song = s_id
LEFT JOIN
author ON a_id = sa_author
GROUP BY
s_name
LIMIT 10
I have a users table with columns: user_id, mechanic_id
and
mechanics table with id
I would like to count how many users have the same mechanic.
Users table
+-------------------------+
| user_Id mechanic_id |
+-------------------------+
| 1 1,2 |
| 2 2,1 |
| 3 2,1,8,16 |
| 4 1,16,3 |
+-------------------------+
mechanics table
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
...
Count for $id1 is: 4
Count for $id2 is: 3
Count for $id3 is: 1
Count for $id8 is: 1
Count for $id16 is: 2
Best solution: scrap this table design and rebuild with a properly normalized once. Then a simple join + group by + count query will work.
Worst solution: use MySQL's find_in_set() function:
SELECT mechanics.id, COUNT(user_ID)
FROM mechanics
LEFT JOIN users ON (FIND_IN_SET(mechanics.id, users.mechanic_id) > 0)
GROUP BY mechanics.id
I don't know why I am violating the basic principles of database normalization...Each user has usually one mechanic or max 2 or 3, so that's why I decided to store data in users table.
I found solution based on #Marc B:
SELECT count(*) FROM users a
INNER JOIN mechanics b
ON (FIND_IN_SET(b.id, a.mechanic_id) > 0)
WHERE b.id = '{$id}'
group by b.id
SELECT COUNT(user_Id)
FROM users, mechanics
WHERE mechanics.id IN (users.mechanic_id)