Run While Loop Through All Distinct Values of A Column - php

This is an example MYSQL result
+----+---+
| A | B |
+----+---+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 3 | 5 |
+----+---+
I would like to run through every distinct in Column A and do something utilizing the values in Column B.
Let's say A has userids and B has foods. I would like to grab all the foods that user 1 likes and then shoot an email to 1, then grab all the foods that user 2 likes and email to her, and so forth. Would appreciate any suggestions.

If you want comma separated values, you can use GROUP_CONCAT
SELECT A, GROUP_CONCAT(DISTINCT B) foodList
FROM tableName
GROUP BY A
SQLFiddle Demo
Other Link
GROUP BY clause

Related

Can SELECT, SELECT COUNT and cross reference tables be handled by just one query?

I have a page that displays a list of projects. With each project is displayed the following data retrieved from a mysqli database:
Title
Subtitle
Description
Part number (1 of x)
The total number of photos associated with that project
A randomly selected photo from the project
A list of tags
Projects are displayed 6 per page using a pagination system
As this is based on an old project of mine, it was originally done with sloppy code (I was just learning and did not know any better) using many queries. Three, in fact, just for items 5-7, and those were contained within a while loop that worked with the pagination system. I'm now quite aware that this is not even close to being the right way to do business.
I am familiar with INNER JOIN and the use of subqueries, but I'm concerned that I may not be able to get all of this data using just one select query for the following reasons:
Items 1-4 are easy enough with a basic SELECT query, BUT...
Item 5 needs a SELECT COUNT AND...
Item 6 needs a basic SELECT query with an ORDER by RAND LIMIT 1 to
select one random photo out of all those associated with each project
(using FilesystemIterator is out of the question, because the photos
table has a column indicating 0 if a photo is inactive and 1 if it is
active)
Item 7 is selected from a cross reference table for the tags and
projects and a table containing the tag ID and names
Given that, I'm not certain if all this can (r even should for that matter) be done with just one query or if it will need more than one query. I have read repeatedly how it is worth a swat on the nose with a newspaper to nest one or more queries inside a while loop. I've even read that multiple queries is, in general, a bad idea.
So I'm stuck. I realize this is likely to sound too general, but I don't have any code that works, just the old code that uses 4 queries to do the job, 3 of which are nested in a while loop.
Database structure below.
Projects table:
+-------------+---------+----------+---------------+------+
| project_id | title | subtitle | description | part |
|---------------------------------------------------------|
| 1 | Chevy | Engine | Modify | 1 |
| 2 | Ford | Trans | Rebuild | 1 |
| 3 | Mopar | Diff | Swap | 1 |
+-------------+---------+----------+---------------+------+
Photos table:
+----------+------------+--------+
| photo_id | project_id | active |
|--------------------------------|
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 2 | 1 |
| 5 | 2 | 1 |
| 6 | 2 | 1 |
| 7 | 3 | 1 |
| 8 | 3 | 1 |
| 9 | 3 | 1 |
+----------+------------+--------+
Tags table:
+--------+------------------+
| tag_id | tag |
|---------------------------|
| 1 | classic |
| 2 | new car |
| 3 | truck |
| 4 | performance |
| 5 | easy |
| 6 | difficult |
| 7 | hard |
| 8 | oem |
| 9 | aftermarket |
+--------+------------------+
Tag/Project cross-reference table:
+------------+-----------+
| project_id | tag_id |
|------------------------|
| 1 | 1 |
| 1 | 3 |
| 1 | 4 |
| 2 | 2 |
| 2 | 5 |
| 3 | 6 |
| 3 | 9 |
+------------+-----------+
I'm not asking for the code to be written for me, but if what I'm asking makes sense, I'd sincerely appreciate a shove in the right direction. Often times I struggle with both the PHP and MySQLi manuals online, so if there's any way to break this down, then fantastic.
Thank you all so much.
You're able to do subqueries inside your SELECT clause, like this:
SELECT
p.title, p.subtitle, p.description, p.part,
(SELECT COUNT(photo_id) FROM Photos where project_id = p.project_id) as total_photos,
(SELECT photo_id FROM Photos where project_id = p.project_id ORDER BY RAND LIMIT 1) as random_photo
FROM projects as p
Now, for the list of tags, as it returns more than one row, you can't do a subquery and you should do one query for every project. Well, in fact you can if you return all the tags in some kind of concatenation, like a comma separated list: tag1,tag2,tag3... but I don't recommend this one time that you will need to explode the column value. Do it only if you have many many projects and the performance to retrieve the list of tags for each individual project is fairly low. If you really want, you can:
SELECT
p.title, p.subtitle, p.description, p.part,
(SELECT COUNT(photo_id) FROM Photos where project_id = p.project_id) as total_photos,
(SELECT photo_id FROM Photos where project_id = p.project_id ORDER BY RAND LIMIT 1) as random_photo,
(SELECT GROUP_CONCAT(tag SEPARATOR ', ') FROM tags WHERE tag_id in (SELECT tag_id FROM tagproject WHERE project_id = p.project_id)) as tags
FROM projects as p
As you said from item 1 to 4 you already have the solution.
Add to the same query a SQL_CALC_FOUND_ROWS instead of a SELECT COUNT to solve the item 5.
For the item 6 you can use a subquery or maybe a LEFT JOIN limiting to one result.
For the latest item you can also use a subquery joining all the tags in a single result (separated by comma for instance).

Using Two Tables in PHP & MySQL to display one loop result

Ok so a bit of a funny question here. I have two tables: -
LiveTable
ArchiveTable
The data is as follows: -
Table: LiveTable Table: ArchiveTable
| ID | NAME | | ID | NAME |
------------------ ------------------
| 1 | Test One | | 4 | Test Four |
------------------ ------------------
| 2 | Test Two | | 5 | Test Five |
------------------ ------------------
| 3 | Test Three| | 6 | Test Six |
What I want to do is merge them into one table for querying purposes only. Not as a Database Structure.
In essence when I do a PHP Loop I want the results to work like this: -
Merged Results
| ID | NAME |
------------------
| 1 | Test One |
------------------
| 2 | Test Two |
------------------
| 3 | Test Three|
------------------
| 4 | Test Four |
------------------
| 5 | Test Five |
------------------
| 6 | Test Six |
How would I go about doing this? Also is there a way of doing this with Doctrine?
You can use an SQL query with UNION:
SELECT ID, Name
FROM LiveTable
UNION ALL
SELECT ID, Name
FROM ArchiveTable
Note: UNION ALL will retain duplicates. If you want to remove duplicate records, then use UNION.
Yould use UNION:
SELECT id, name FROM tbl1
UNION ALL
SELECT id, name FROM tbl2
Create DB view using above two tables
CREATE VIEW view_name AS SELECT
id, name FROM tbl1
UNION
id, name FROM tbl2
Then you can query on your view
you can use the sql query multi table select
Select * from LiveTable,ArchiveTable
that's it

how to select data that have the same value with sql?

I have a table with three columns, id, name, and value, as shown below. I want to count the average where the id and value columns are the same, how can I do this?
+----+--------+-------+
| id | name | value |
+----+--------+-------+
| 2 | rahmat | 3 |
| 2 | olive | 5 |
| 3 | sari | 3 |
| 3 | ryan | 2 |
| 1 | zaki | 1 |
+----+--------+-------+
Try using this query:
SELECT AVG(value)
FROM table
WHERE id = value
The output from the sample table you gave in your OP would be 1.5, since sari and zaki are the only 2 users whose records have id and value columns which are equal.
according to your question yes you need to use
SELECT AVG(value)
FROM #table
WHERE id = value
I have created a sqlfiddle here
http://sqlfiddle.com/#!3/9eecb7/4105
from the nature of this question I feel you trying to calculate average of values of those rows having same ids. If that's the case I have created another fiddle http://sqlfiddle.com/#!3/9eecb7/4110 where you need to use group by
select id, sum(value)/count(id) as average from #table group by id
Lemme know if it is something you are after or you need something else.

MySQL sum of distinct rows

I have a query performing INNER JOINs pulling in a relational cross reference table. So based on the query, I'm getting all (one to many) 'fruits' related to a basket. I need to sum the amount of fruits distinctly.
| Banana | 1 |
| Banana | 1 |
| Apple | 1 |
| Pear | 1 |
| Pear | 1 |
| Pear | 1 |
I want the result set to look like this...
| Banana | 2 |
| Apple | 1 |
| Pear | 3 |
I tried to SUM() fruit in the SELECT with a GROUP BY but the results were not correct (way off). I'm thinking HAVING might need to come into play... anyway, frustrated since this should be pretty easy.
If there are only 1's in the second column, try:
SELECT fruit, count(fruit)
FROM fruits_table
GROUP BY fruit
Not too difficult with a SUM() and GROUP BY:
select a.fruit, sum(a.num) as number
from fruits a
group by a.fruit;
SQLFiddle: http://sqlfiddle.com/#!2/3b53a/1
Try this code:
select fruit_name, sum(qte)
from fruit_table_name
group by fruit_name;

query to imlement block list

I have two tables a and b as follows to implement a simple block list where users can block other users.....
Table A
+------------+--------------+------+
| Name | phone |userid|
+------------+--------------+------+
| Mr Sasi | 01225 708225 | 1 |
| Miss Brown | 01225 899360 | 2 |
| Mr Black | 01380 724040 | 3 |
+------------+--------------+------+
Table B
+------------+--------------+
| blockedbyid| blockedid |
+------------+--------------+
| 1 | 2 |
| 2 | 3 |
| 1 | 3 |
+------------+--------------+
"blockedbyid" is id of user who has blocked the user in "blockedid".
I need to join the two tables and fetch all records from table A such that the result has all users who are not blocked by a particular user [ie blockedbyid='XXX'].. Can you guys give the SQL query so that i can fetch the records as a recordset??? I dont want to fetch two different rowsets and compare it in php....
Something like this should work
Parameter :USERID
SELECT * FROM TABLEA WHERE userid NOT IN (SELECT blockedid FROM TABLEB WHERE blockedbyid = :USERID)
Using join
SELECT u.* FROM TABLEB b, TABLEA u WHERE b.blockedbyid = 'XXX' AND b.blockedid = NULL
It may work like that, give it a try.
Roadie57 solutions seems better though.

Categories