How to count by joining two tables - mysql

I have 2 tables like this.
Table : Family Members
----------------------------------
|Address | Name |
----------------------------------
|North Jakarta City | Andra |
|North Jakarta City | Halim |
|South Jakarta City | Irma |
|Thousand Island Village | Dian |
----------------------------------
Table : Member Details
---------------
| Name | Age |
---------------
| Andra | 1 |
| Halim | 50 |
| Irma | 20 |
| Dian | 4 |
---------------
What is the correct query if I want to count members between the ages 0 and 4 who live in a 'city'? I've tried using this query but the result is incorrect. The correct result should be 1 since only Andra who lives in a city and between the ages 0 and 4. Please help me.
SELECT COUNT(family_members.name) AS total FROM family_members, member_details
WHERE family_members.address LIKE '%City%' AND member_details.age BETWEEN 0 AND 4

You need a join
SELECT COUNT(fm.name) AS total
FROM family_members fm
Join member_details md on md.Name = fm.Name
WHERE fm.address LIKE '%City%' AND md.age BETWEEN 0 AND 4
with you syntax, you may add this in the where clause (because your query will generate a cartesian product).
BUT : you should really use the JOIN syntax
AND family_members.Name = member_details.Name
EDIT
By the way, I would strongly suggest to use surrogate keys in your tables (a name is not really something unique)

You should consider redesigning your database like:
----------------------------------
| user_id | Name | Age | city_id |
----------------------------------
| 1 | Andra | 1 | 1 |
| 2 | Halim | 50 | 1 |
| 3 | Irma | 20 | 1 |
| 4 | Dian | 4 | 2 |
----------------------------------
------------------------------------
|city_name | city_id |
------------------------------------
|North Jakarta City | 1 |
|Thousand Island Village | 2 |
------------------------------------
SELECT COUNT(*) AS total
FROM family_member
JOIN city on family_member.city_id = city.city_id
WHERE city.city_name= 'City' AND family_member.age BETWEEN 0 AND 4;
Also you should add indexes.

Related

Join 2 tables and sum with condition in codeigniter

I have 2 tables
Table1: customers:
-------------
| id | name |
-------------
| 1 | Mark |
-------------
| 2 | Tom |
-------------
| 3 | John |
Table2: sales:
-----------------------------------
|sid | customerid | price | state |
-----------------------------------
| 10 | 1 | 12000 | 0 |
-----------------------------------
| 11 | 2 | 13500 | 1 |
-----------------------------------
| 12 | 2 | 23000 | 1 |
-----------------------------------
| 13 | 3 | 26000 | 0 |
-----------------------------------
| 14 | 1 | 66000 | 1 |
-----------------------------------
the state column is 0=no dep and 1=dept
I want to list the customers that have DEPT by checking them in the sales table. Now i'm looping the customers and checking them one by one. and it works! but when the number of rows in the customer table grows the page slows down. i want to make this by an SQL query. can anyone help me please ?
the result will be like this:
Mark 66000
Tom 36500
By the Following query, you will get the same output as you want. The joining of tables will be executed on the filtered data using where condition
$this->db->select('customers.name,sum(sales.price)')
->from('customers')
->join('sales','sales.customerid = customers.id','left')
->where('sales.state !=0')
->group_by('customers.name');
->get()->result_array();
You can simply group by customer id in sales table. Code will be like this
return $this->db->select('MAX(customers.name) AS name, SUM(sales.price) as price')->join('sales', 'sales.customerid = customers.id')->where('sales.state', 1)->group_by('customers.id')->get('customers')->result();

mySQL SELECT query from multiple tables

I need a help with mySQL SELECT query from multiple tables. I have got four tables: school, discipline, pupils and teams.
School table looks like:
+------+---------+---------------+----------+
| id | name | discipline_id | pupil_id |
+------+---------+---------------+----------+
| 1 | one | 2 | 5 |
+------+---------+---------------+----------+
| 2 | two | 3 | 8 |
+------+---------+---------------+----------+
| 3 | three | 4 | 12 |
+------+---------+---------------+----------+
Discipline table looks like:
+------+---------+
| id | name |
+------+---------+
| 1 | math |
+------+---------+
| 2 | bio |
+------+---------+
| 3 | liter |
+------+---------+
| 4 | geo |
+------+---------+
Teams table looks like:
+------+---------+---------------+-----------+
| id | name | school_id | member_id |
+------+---------+---------------+-----------+
| 1 | T1 | 1 | 3 |
+------+---------+---------------+-----------+
| 2 | T2 | 3 | 3 |
+------+---------+---------------+-----------+
| 3 | T3 | 2 | 9 |
+------+---------+---------------+-----------+
The result of disciplines I need to get with a "SELECT from discipline..." query by "member_id = 3" is:
+-----------------+---------------+
| discipline_name | discipline_id |
+-----------------+---------------+
| bio | 2 |
+-----------------+---------------+
| geo | 4 |
+-----------------+---------------+
By matching member's school and then getting its discipline, if it makes sense...Is it possible to do with just one mySQL query?
Type of: member_id 3 => school_id 1,3 => discipline_id = show related disciplines names and ids which are 2, 4
Thank you very much...
Your goal is not clear or makes no sense to me.
But here is what you are literally asking for:
SELECT
s.discipline_id
d.name
FROM teams t
LEFT JOIN school s
ON s.id = t.school_id
LEFT JOIN discipline d
ON d.id = s.discipline_id
WHERE t.member_id = 3

mysql query using inner joins and subquery

These are the tables:
professor:
+-------+--------+--------+--------+------+
| empid | name | status | salary | age |
+-------+--------+--------+--------+------+
| 1 | Arun | 1 | 2000 | 23 |
| 2 | Benoy | 0 | 3000 | 25 |
| 3 | Chacko | 1 | 1000 | 36 |
| 4 | Divin | 0 | 5000 | 32 |
| 5 | Edwin | 1 | 2500 | 55 |
| 7 | George | 0 | 1500 | 46 |
+-------+--------+--------+--------+------+
works:
+----------+-------+---------+
| courseid | empid | classid |
+----------+-------+---------+
| 1 | 1 | 10 |
| 2 | 2 | 9 |
| 3 | 3 | 8 |
| 4 | 4 | 10 |
| 5 | 5 | 9 |
| 6 | 1 | 9 |
| 2 | 3 | 10 |
| 2 | 1 | 7 |
+----------+-------+---------+
course:
+----------+------------+--------+
| courseid | coursename | points |
+----------+------------+--------+
| 1 | Maths | 100 |
| 2 | Science | 80 |
| 3 | English | 85 |
| 4 | Social | 90 |
| 5 | Malayalam | 99 |
| 6 | Arts | 40 |
+----------+------------+--------+
The question is :
Return list of employees who have taught course Maths or Science but
not both
The query which I wrote is :
select distinct professor.name from professor
inner join works
on professor.empid=works.empid
where works.courseid in
(select courseid from course where coursename ='Maths' or coursename='Science');
The output I received is:
Arun
Benoy
Chacko
Here the employee 'Arun' shouldnt have been displayed as he as taught both Maths and Science.
Please help me out !!
You may use an aggregate COUNT() to check that the total number of DISTINCT courses taught is exactly 1, while still filtering to the two different types of courses. That ensures that only one, never both, is returned.
Because the IN () limits all rows initially returned only to the two desired courses, professors can have a maximum of 2 possible different courses via COUNT(DISTINCT coursename). A HAVING clause then prohibits those with 2 from the final result set.
SELECT
DISTINCT professor.name
FROM
professor
INNER JOIN works ON professor.empid = works.empid
/* Join against course to get the course names */
INNER JOIN course ON works.courseid = course.courseid
WHERE
/* Restrict only to Maths, Science */
course.coursename IN ('Maths', 'Science')
GROUP BY professor.name
/* Only those with exactly one type of course */
HAVING COUNT(DISTINCT course.coursename) = 1
Here is a demonstration: http://sqlfiddle.com/#!2/2e9610/2
You want to use an xor here instead of an or.
select distinct professor.name from professor
inner join works
on professor.empid=works.empid
where works.courseid in
(select courseid from course where coursename ='Maths' xor coursename='Science');

Query that display father, son in one column

I use MySQL,
In my database, I have this table :
+-----------------------------+
| ID NAME ID_FATHER |
+-----------------------------+
| 1 Mylodi 0 |
| 2 Jack 0 |
| 3 Linda 1 |
| 4 Mark 2 |
| 5 Simon 4 |
| 6 Sacha 1 |
| 7 Edward 1 |
+-----------------------------+
By this query I retrieve each name with his father :
select f.name as father, s.name as son from family s, family f where s.id_father = f.id
Result
+------------+---------+
| father | son |
+------------+---------+
| mylodi | linda |
| Jack | mark |
| mark | simon |
| mylodi | sacha |
| mylodi | edward |
+------------+---------+
But, my question How can I get this result, but in one column like this :
+--------+
| colum |
+--------+
| Mylodi |
| linda |
| sacha |
| edward |
| jack |
| mark |
| simon |
+--------+
that mean I want to display the name of the Father and of below each name of father names of his son. Thanks.
EDIT
this is my db structure
How about something like this:
SELECT name FROM (
SELECT id, name, id sort1, id_father sort2 FROM family WHERE id_father = 0
UNION
SELECT id, name, id_father, 1 sort2 FROM family WHERE id_father <> 0
) AS v
ORDER BY sort1, sort2
Here's an updated fiddle.
This is not so straightforward. It assumes that there are no loops in the data (a is b's father and b is a's father)
Not sure what database you are using, but Oracle has Hierarchical queries that are meant for problems like this using the "connect by" keyword.

Trouble writing MySQL query involving ordered data from three tables

I have a table called tags, like this:
+-------+----------+
| tagID | tagName |
+-------+----------+
| 1 | jewelery |
| 2 | gifts |
| 3 | asdf |
| 4 | fashion |
| 5 | diamonds |
+-------+----------+
Then a table called coupon_tags, like this:
+-------+----------+
| tagID | couponID |
+-------+----------+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 3 |
+-------+----------+
And lastly, a table called coupons, here are the pertinent parts (id is the same as couponID elsewhere):
+----+-----------------+
| id | zone |
+----+-----------------+
| 1 | Los Angeles |
| 2 | Orange County |
| 3 | Los Angeles |
| 5 | Orange County |
| 6 | Orange County |
+----+-----------------+
What I need to write a query for: I want to get tagNames via the first table that correspond to the ordered list of the top 10 most used tagIDs in the second table, but it only looks through couponIDs that match another criteria - that the "zone" be a certain zone. In the end, only the top 10 tagNames from a certain zone will show. I've never done a triple-table query before, any help?
I'm trying to keep this purely SQL, as I had a partially working PHP solution but it was messy and very slow.
SELECT tags.tagName FROM
(SELECT tagID, COUNT(*) FROM
coupon_tags
JOIN coupons ON coupons.couponID = coupon_tags.couponID AND zone = 'Los Angeles'
GROUP BY tagID ORDER BY COUNT(*) DESC LIMIT 10) AS most_used
JOIN tags ON most_used.tagID = tags.tagID