grouping join query results - mysql

I am trying to write a query that shows me all orders with their options. So far that's done, but when I try to group them by order id it just print a separate row for each option and not the order ID and all its option under it.
I am missing something but can't figure out what is it :)
Here is what I have
$sql = 'SELECT *
FROM `order` RIGHT JOIN `order_option`
on order.order_id=order_option.order_id
where order_status_id = 2
group by order_option.order_option_id';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
print "ID:{$row['order_id']} <br> ".
"OPTION NAME: {$row['name']} <br> ".
"VALUE: {$row['value']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
**UPDATE 1**
This is how the query worked now
SELECT
o.order_id,
o.name,
o.value,
GROUP_CONCAT(o.order_id, o.name, o.value SEPARATOR ',') AS Options
FROM `order_option` AS o
LEFT JOIN `order` AS oo on o.order_id = oo.order_id
where oo.order_status_id = 2
group by o.order_id

You should GROUP BY order_id instead, and use GROUP_CONCAT to get all the options of an order in the same row:
SELECT
o.order_id,
GROUP_CONCAT(oo.order_option_id SEPARATOR ',') AS Options
FROM `order` AS o
RIGHT JOIN `order_option` AS oo on o.order_id = oo.order_id
where o.order_status_id = 2
group by o.order_id;
SQL Fiddle Demo
If GROUP_CONCAT is not what are you looking for, then you have to use other aggregate functions, but don't include any columns that is not in the GROUP BY clause in the SELECT clause without an aggregate function. Otherwise you will got inconsistent data.
Update 1
The reason your query doesn't work:
SELECT
o.order_id,
o.name,
o.value,
GROUP_CONCAT(o.order_id SEPARATOR ',') AS Options
FROM order_option AS o
LEFT JOIN order AS oo on o.order_id = oo.order_id
where oo.order_status_id = 2
group by o.order_id
Becuase the two columns o.name, o.value in the SELECT clause are not neither in an aggregate function not in the GROUP BY clause, so you are getting inconsistent values of these tow columns, MySQL gets an arbitrary value for them. Try this instead:
SELECT
o.order_id,
o.name,
o.value,
GROUP_CONCAT(o.order_id SEPARATOR ',') AS Options
FROM order_option AS o
LEFT JOIN order AS oo on o.order_id = oo.order_id
where oo.order_status_id = 2
group by o.order_id,
o.name,
o.value;

Related

SQL Query that inner joins on a certain condition

I have this Sql query which I use to create a view. But I need to refactor it, thus it will only perform inner join when SALES.PKY has a duplicate value or is not unique. How can I do it in a single query?
SELECT *
FROM SALES
INNER JOIN MAIN ON
REPLACE(MAIN.KEY,'-','') = SALES.PKY
AND REPLACE (MAIN.B,' ','') = SALES.SK
AND REPLACE (MAIN.P,' ','') = SALES.SP
could you use a with statement to filter like this?
with dups as (
select *
from sales
group by dup_value
having dup_value>1
)
select
dups.*
,main.*
from dups
inner join main
on dups_key=main_key
Here is one method:
SELECT *
FROM SALES INNER JOIN
MAIN
ON REPLACE(MAIN.KEY,'-','') = SALES.PKY AND
REPLACE(MAIN.B,' ','') = SALES.SK AND
REPLACE(MAIN.P,' ','') = SALES.SP JOIN
(SELECT s.PKY
FROM SALES s
GROUP BY s.PKY
HAVING COUNT(*) > 1
) ss
ON ss.PKY = SALES.PKY;

how to use select sub query in other query MySQL

I am writing a mysql select sub query, that is working fine, it returns 2 column is there way to select only 1 column.
My query is
SELECT sum(fl.qunt) as qunt,(
SELECT GROUP_CONCAT( xp.id
SEPARATOR ',' )
FROM prdt AS xp
LEFT JOIN prdt_fac AS pf ON pf.fk_product_children = xp.rowid
WHERE pf.prdt_fat = p.id
AND pf.prdt_ch = 6953
GROUP BY pf.prdt_fat
LIMIT 0 , 1
) AS prdt_chd
FROM fac_log AS fl
LEFT JOIN fac AS f ON fl.fac = f.id
LEFT JOIN prdt AS p ON f.prdt = p.id
GROUP BY prod_child
ORDER BY fl.tms DESC
LIMIT 0 , 1
This return two column qunt and prdt_ch.
But i want only column in result qunt.
Is there any way, becuase inner select query is must be used to get correct result.
Main purpose of this query is that i have to use this query as sub query in an other query, in this condition it throws error "operand should contain 1 column"
Thanks in advance
just select qunt using your select query as a table (t)
select qunt from (
SELECT sum(fl.qunt) as qunt,(
SELECT GROUP_CONCAT( xp.id
SEPARATOR ',' )
FROM prdt AS xp
LEFT JOIN prdt_fac AS pf ON pf.fk_product_children = xp.rowid
WHERE pf.prdt_fat = p.id
AND pf.prdt_ch = 6953
GROUP BY pf.prdt_fat
LIMIT 0 , 1
) AS prdt_chd
FROM fac_log AS fl
LEFT JOIN fac AS f ON fl.fac = f.id
LEFT JOIN prdt AS p ON f.prdt = p.id
GROUP BY prod_child
ORDER BY fl.tms DESC
LIMIT 0 , 1 ) t

invalid use of group in mysql

I have the following query:
return $this->createQueryBuilder('s')
->select('DISTINCT s.username')
->addSelect('COUNT(p.id) as HIDDEN c_id')
->leftJoin('s.owner', 'o')
->leftJoin('s.userPictures', 'p')
->leftJoin('o.transactions', 't')
->leftJoin('t.packType', 'pt')
->where('pt.id =:packId')
->setParameter('packId', $packId)
->andWhere('s.expirydate >=:expiryDate')
->setParameter('expiryDate', new \DateTime('now'))
->andWhere('COUNT(p.id) <:numberOfPictures')
->setParameter('numberOfPictures', $numberOfPictures)
->groupBy('p.shop')
->orderBy("c_id", 'ASC')
->getQuery()
->getResult()
;
however when trying to run this I always get invalid use of group function. Why is this?
Here's the real SQL query when translated:
SELECT DISTINCT s.username, COUNT(p.id) as HIDDEN c_id
FROM App\MainBundle\Entity\InstagramShop s
LEFT JOIN s.owner o
LEFT JOIN s.userPictures p
LEFT JOIN o.transactions t
LEFT JOIN t.packType pt
WHERE pt.id =:packId AND s.expirydate >=:expiryDate AND COUNT(p.id) <:numberOfPictures
GROUP BY p.shop
ORDER BY c_id ASC

How can I merge these SQL queries

I need to merge this query
SELECT
*,
(SELECT
CONCAT(c.firstname, ' ', c.lastname)
FROM
wwwpser_customer c
WHERE
c.customer_id = o.customer_id) AS customer
FROM
wwwpser_order o
WHERE
o.order_id = '20'
with
SELECT
orders . *, wwwpser_comuna.provincia_id AS payment_provincia_id
FROM
wwwpser_order orders
LEFT JOIN
wwwpser_comuna ON (orders.payment_city = wwwpser_comuna.comuna_id)
SQL syntax is new for me so I need a little help with this, thx
SELECT CONCAT(c.firstname, ' ', c.lastname)
, wc.provincia_id
, o.*
FROM wwwpser_order o
LEFT JOIN
wwwpser_customer c
ON c.customer_id = o.customer_id
LEFT JOIN
wwwpser_comuna wc
ON wc.comuna_id = o.payment_city
WHERE o.order_id = 20
It looks like this should be your solution.
SELECT
o.*, -- modified (qualified the
(SELECT -- asterisk)
CONCAT(c.firstname, ' ', c.lastname)
FROM
wwwpser_customer c
WHERE
c.customer_id = o.customer_id) AS customer,
c.provincia_id AS payment_provincia_id -- added from second query
FROM
wwwpser_order o
LEFT JOIN -- added from second query
wwwpser_comuna c ON (o.payment_city = c.comuna_id) -- added from second query
WHERE
o.order_id = '20'
I strongly recommend learning about the general SQL syntax, though. There are some useful examples in the MySQL tutorials

Multiple many-to-many JOINs in a single mysql query without Cartesian Product

At the moment I can get the results I need with two seperate SELECT statements
SELECT
COUNT(rl.refBiblioID)
FROM biblioList bl
LEFT JOIN refList rl ON bl.biblioID = rl.biblioID
GROUP BY bl.biblioID
SELECT
GROUP_CONCAT(
CONCAT_WS( ':', al.lastName, al.firstName )
ORDER BY al.authorID )
FROM biblioList bl
LEFT JOIN biblio_author ba ON ba.biblioID = bl.biblioID
JOIN authorList al ON al.authorID = ba.authorID
GROUP BY bl.biblioID
Combining them like this however
SELECT
GROUP_CONCAT(
CONCAT_WS( ':', al.lastName, al.firstName )
ORDER BY al.authorID ),
COUNT(rl.refBiblioID)
FROM biblioList bl
LEFT JOIN biblio_author ba ON ba.biblioID = bl.biblioID
JOIN authorList al ON al.authorID = ba.authorID
LEFT JOIN refList rl ON bl.biblioID = rl.biblioID
GROUP BY bl.biblioID
causes the author result column to have duplicate names. How can I get the desired results from one SELECT statement without using DISTINCT? With subqueries?
If subselects are acceptable, I believe you could make this happen by doing something like this:
SELECT
y.authors,
COUNT(rl.refBiblioID)
FROM
(SELECT
bl.biblioId,
GROUP_CONCAT(
CONCAT_WS(':', al.lastName, al.firstName)
ORDER BY al.authorID) AS authors
FROM biblioList bl
LEFT JOIN biblio_author ba ON ba.biblioID = bl.biblioID
JOIN authorList al ON al.authorID = ba.authorID
GROUP BY bl.biblioID) y
LEFT JOIN refList rl ON (y.biblioID = rl.biblioID)
GROUP BY y.biblioID
Another solution would be to add DISTINCT to your GROUP_CONCAT, but that was not what you wanted?
GROUP_CONCAT(
DISTINCT(CONCAT_WS(':', al.lastName, al.firstName) ORDER BY al.authorID)),