mysql joins and groups - mysql

I'm new to this forum from the standpoint of posting, as this question may show. I'm having some issues with the way I want my data to appear.
So, I have 3 tables (I am only showing the columns that I want):
visitors:
center_id (where the visitor was) | state_id (where they came from)
centers:
center_id | center
states:
state_id | state
here is the query that I have been using
SELECT states.state, visitors.center_id, visitors.state_id, centers.center, COUNT(visitors.state_id) AS totalCount
FROM visitors
LEFT JOIN states ON states.state_id = visitors.state_id
LEFT JOIN centers ON centers.center_id = visitors.center_id
WHERE visitors.vdate = <some date> AND visitors.state_id <> '0'
GROUP BY centers.center, visitors.state_id
This produces the following array:
Array
(
[0] => Array
(
[state] => Connecticut
[location_id] => 1
[state_id] => 8
[center] => Little River
[totalCount] => 1
)
[1] => Array
(
[state] => California
[location_id] => 5
[state_id] => 6
[center] => North Augusta
[totalCount] => 1
)
[2] => Array
(
[state] => Colorado
[location_id] => 5
[state_id] => 7
[center] => North Augusta
[totalCount] => 2
)
[6] => Array
(
[state] => Connecticut
[location_id] => 9
[state_id] => 8
[center] => Santee
[totalCount] => 2
)
[7] => Array
(
[state] => Virginia
[location_id] => 9
[state_id] => 51
[center] => Santee
[totalCount] => 1
)
)
This is what I really want:
Array
(
[Little River] => Array
(
[0] => Array
(
[state] => Connecticut
[state_id] => 8
[totalCount] => 1
)
)
[North Augusta] => Array
(
[0] => Array
(
[state] => California
[state_id] => 6
[totalCount] => 1
)
[1] => Array
(
[state] => Colorado
[state_id] => 7
[totalCount] => 2
)
)
[Santee] => Array
(
[0] => Array
(
[state] => Connecticut
[state_id] => 8
[totalCount] => 2
)
[1] => Array
(
[state] => Virginia
[state_id] => 51
[totalCount] => 1
)
)
)
Ultimately I'm putting this into a table that looks something like this:
__________________
|State | Count|
-------------------
| Santee |
-------------------
| Georgia | 5 |
-------------------
| Alabama | 10 |
-------------------
| North Augusta |
-------------------
| another | 7 |
-------------------
Sorry for being long winded, but this was the only way that I could describe it.
I've also tried breaking it out in php, but I'm probably doing something wrong there too. I can make a table with 3 columns with the center listed with each state, but I'm realliy looking for a row that show the center followed by all of the states and counts for that center and on to the next center.
Any assistance would be appreciated.

A query may only return a two- (or less) dimentional result. You will need to parse this result set to transform it into a tree.
With PHP, there really is no difficulty:
foreach ($rawResultSet as $row) {
$finalResult[$row['center']][] = array(
$row['state'],
$row['state_id'],
$row['totalCount']
);
}

Related

MySQL join same column name [duplicate]

This question already has an answer here:
MySQL JOIN tables with duplicate column names
(1 answer)
Closed 3 years ago.
Right now I have this code:
SELECT * FROM orders, products WHERE product_id=products.id AND `geleverd` = 0
Wich returns as this:
I also have this code for a button:
echo "<a onclick='return window.confirm(\"Weet je zeker dat ".$row['merk']." ".$row['model']." geleverd is?\")' href='change_order_status.php?id=". $row['id'] ."' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-ok' style='color:black'></span></a>";
But for some reason id returns a 9 instead of a 1
This is the output of a print of $row
Array
(
[0] => 1
[id] => 9
[1] => 2019-1
[ordernummer] => 2019-1
[2] => 9
[product_id] => 9
[3] => 2
[aantal] => 2
[4] => aaa
[omschrijving] => aaa
[5] => 0
[geleverd] => 0
[6] => 9
[7] => Samsung
[merk] => Samsung
[8] => Tablet S2
[model] => Tablet S2
[9] => 1
[threshold] => 1
)
and:
(
[0] => 3
[id] => 9
[1] => 789
[ordernummer] => 789
[2] => 9
[product_id] => 9
[3] => 10
[aantal] => 10
[4] => test
[omschrijving] => test
[5] => 0
[geleverd] => 0
[6] => 9
[7] => Samsung
[merk] => Samsung
[8] => Tablet S2
[model] => Tablet S2
[9] => 1
[threshold] => 1
)
How can I fix that Id will be 1 for the first row and not 9 and for the second row id will be 3 instead of 9
You need to use Alias for the tables, and combine/rename the columns that you need.
SELECT o.id as orderId, p.id as productId, -all the columns you need with the alias first- FROM orders as o, products as p WHERE o.product_id=p.id AND `geleverd` = 0

How to convert MySQL rows into formatted json objects [duplicate]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an array that looks like this. This is a 2 dimensional array.
$MainArray = Array
(
[0] => Array
(
[Job_Name] => WXYZ
[Quantity] => 1000
[Machine_Name] => Machine1
[Start_Date] => 2014-07-30 00:00:00
[Completion_Date] => 2014-08-02 00:00:00
[Labor] => 4
)
[1] => Array
(
[Job_Name] => ABCD
[Quantity] => 1500
[Machine_Name] => Machine2
[Start_Date] => 2014-08-08 00:00:00
[Completion_Date] => 2014-08-14 00:00:00
[Labor] => 2
)
[2] => Array
(
[Job_Name] => BCDA
[Quantity] => 1200
[Machine_Name] => Machine1
[Start_Date] => 2014-08-02 00:00:00
[Completion_Date] => 2014-08-07 00:00:00
[Labor] => 1
)
)
I want to use this information to create a new 3 dimensional array that looks like this.
$ConvertedArray = Array
(
[Machine1] => Array
(
[0] => Array
(
[Job_Name] => WXYZ
[Quantity] => 1000
[Start_Date] => 2014-07-30 00:00:00
[Completion_Date] => 2014-08-02 00:00:00
[Labor] => 4
)
[1] => Array
(
[Job_Name] => BCDA
[Quantity] => 1200
[Start_Date] => 2014-08-02 00:00:00
[Completion_Date] => 2014-08-07 00:00:00
[Labor] => 1
)
)
[Machine2] => Array
(
[0] => Array
(
[Job_Name] => ABCD
[Quantity] => 1500
[Machine_Name] => Machine2
[Start_Date] => 2014-08-08 00:00:00
[Completion_Date] => 2014-08-14 00:00:00
[Labor] => 2
)
)
)
Please any help on this would be appreciated. I am stuck with something and need to figure out how to create the new array using this original array. So basically I am grouping all the jobs from each machine together and the keys for those jobs depend on how they are in the original array. So if the original array has a job with the key 2 and no other job has a higher key on that machine, then it will become key 0 for that job and create a new key with that machine name.
I really appreciate your help on this.
Use below code:-
$result = [];
foreach($MainArray as $record){
$result[$record['Machine_Name']][] = $record;
}
foreach ($MainArray as $value) {
$name = $value['Machine_Name'];
unset($value['Machine_Name']);
$ConvertedArray[$name][] = $value;
}

Getting multiple rows of same row with just one column change from database

I'm using following query to fetch record from database. It has join with to many other tables. Everything work fine but problem is I'm getting multiple rows of same reservation and it's because reservation table has join with payment table and payment table has multiple rows against one reservation that's why it repeat complete record. What I want is to show single row having all payments rows in it so that I can loop through all payments and display them instead of displaying entire reservation record again and again. below is my query. It's Laravel 5.2.
return $results = DB::table('resorts_reservation')
->join('resorts_resort', 'resorts_reservation.resortId', '=', 'resorts_resort.resortId')
->join('resorts_roomtype', 'resorts_reservation.roomTypeId', '=', 'resorts_roomtype.roomTypeId')
->join('resorts_customer', 'resorts_reservation.customerId', '=', 'resorts_customer.customerId')
->join('resorts_salesperson', 'resorts_reservation.salesPersonId', '=', 'resorts_salesperson.salesPersonId')
->join('resorts_payment', 'resorts_reservation.reservationId', '=', 'resorts_payment.reservationId')
->join('resorts_paymentmethod', 'resorts_payment.paymentMethodId', '=', 'resorts_paymentmethod.paymentMethodId')
->join('resorts_emailnotification', 'resorts_reservation.reservationId', '=', 'resorts_emailnotification.reservationId')
->join('resorts_resortcompany', 'resorts_resort.resortCompanyId', '=', 'resorts_resortcompany.resortCompanyId')
->select('resorts_reservation.totalAmount', 'resorts_reservation.saleDate', 'resorts_reservation.reservationId',
'resorts_reservation.confirmNo', 'resorts_reservation.numberOfNights', 'resorts_reservation.checkInDate',
'resorts_reservation.checkOutDate', 'resorts_reservation.numberOfAdults', 'resorts_reservation.numberOfChildren',
'resorts_reservation.totalInParty', 'resorts_reservation.notes', 'resorts_reservation.totalPrice',
'resorts_reservation.saleSource', 'resorts_reservation.depositAmount', 'resorts_reservation.confirmationSent',
'resorts_reservation.finalized',
'resorts_customer.firstName', 'resorts_customer.mobilePhone', 'resorts_customer.otherPhone',
'resorts_customer.email', 'resorts_customer.addressLineOne', 'resorts_customer.city',
'resorts_customer.country', 'resorts_customer.state_', 'resorts_customer.postalCode',
'resorts_resort.resortName',
'resorts_roomtype.roomTypeDesc', 'resorts_roomtype.occupancy',
'resorts_salesperson.firstName as saleFirstName','resorts_salesperson.lastName as saleLastName',
'resorts_paymentmethod.methodType',
'resorts_payment.transactionNo',
'resorts_resortcompany.resortCompanyName')
->whereRaw($where)
->orderBy('reservationId', 'desc')
->get();
Below is the result return from the query. You can see both rows has same record with just "transactionNo" column change.
[0] => stdClass Object
(
[totalAmount] => 2161.2
[saleDate] => 2016-03-09 00:00:00
[reservationId] => 30286
[confirmNo] =>
[numberOfNights] => 3
[checkInDate] => 2016-04-22 00:00:00
[checkOutDate] => 2016-04-25 00:00:00
[numberOfAdults] => 6
[numberOfChildren] => 0
[totalInParty] => 6
[notes] =>
[totalPrice] => 2161.2
[saleSource] => VRBO
[depositAmount] => 2161.2
[confirmationSent] => 0
[finalized] => 0
[firstName] => Michael
[mobilePhone] => 505-321-2106
[otherPhone] =>
[email] => xxxxxxxx#gmail.com
[addressLineOne] =>
[city] => Albuquerque
[country] => USA
[state_] => NM
[postalCode] => 87111
[resortName] => San Francisco - Canterbury
[roomTypeDesc] => 3 Bedroom Presidential
[occupancy] => 6
[saleFirstName] => Kristy
[saleLastName] => Conlin
[methodType] => CREDIT_CARD
[transactionNo] => 7MG983973K453254C
[resortCompanyName] => Wyndham
)
[1] => stdClass Object
(
[totalAmount] => 2161.2
[saleDate] => 2016-03-09 00:00:00
[reservationId] => 30286
[confirmNo] =>
[numberOfNights] => 3
[checkInDate] => 2016-04-22 00:00:00
[checkOutDate] => 2016-04-25 00:00:00
[numberOfAdults] => 6
[numberOfChildren] => 0
[totalInParty] => 6
[notes] =>
[totalPrice] => 2161.2
[saleSource] => VRBO
[depositAmount] => 2161.2
[confirmationSent] => 0
[finalized] => 0
[firstName] => Michael
[mobilePhone] => 505-321-2106
[otherPhone] =>
[email] => xxxxxxxx#gmail.com
[addressLineOne] =>
[city] => Albuquerque
[country] => USA
[state_] => NM
[postalCode] => 87111
[resortName] => San Francisco - Canterbury
[roomTypeDesc] => 3 Bedroom Presidential
[occupancy] => 6
[saleFirstName] => Kristy
[saleLastName] => Conlin
[methodType] => CREDIT_CARD
[transactionNo] =>
[resortCompanyName] => Wyndham
)
What I want is something like below:
[0] => stdClass Object
(
[totalAmount] => 2161.2
[saleDate] => 2016-03-09 00:00:00
[reservationId] => 30286
[confirmNo] =>
[numberOfNights] => 3
[checkInDate] => 2016-04-22 00:00:00
[checkOutDate] => 2016-04-25 00:00:00
[numberOfAdults] => 6
[numberOfChildren] => 0
[totalInParty] => 6
[notes] =>
[totalPrice] => 2161.2
[saleSource] => VRBO
[depositAmount] => 2161.2
[confirmationSent] => 0
[finalized] => 0
[firstName] => Michael
[mobilePhone] => 505-321-2106
[otherPhone] =>
[email] => xxxxxxxx#gmail.com
[addressLineOne] =>
[city] => Albuquerque
[country] => USA
[state_] => NM
[postalCode] => 87111
[resortName] => San Francisco - Canterbury
[roomTypeDesc] => 3 Bedroom Presidential
[occupancy] => 6
[saleFirstName] => Kristy
[saleLastName] => Conlin
[methodType] => CREDIT_CARD
array(
[transactionNo] => 7MG983973K453254C
[transactionNo] =>
)
[resortCompanyName] => Wyndham
)
You can use GROUP-CONCAT function to group all payment transaction numbers for each reservation.
From MySQL docs
This function returns a string result with the concatenated non-NULL
values from a group. It returns NULL if there are no non-NULL values.
Your query will look something like this:
SELECT resorts_reservation.totalAmount, ..., GROUP_CONCAT(resorts_payment.transactionNo separator ', ') as transactionNoList
WHERE...
Hope this makes sense, if not, I will be glad to clarify.
Tom Rushman

MySQL select multiple rows from two tables, group by row from one table

I have two tables:
1)
CREATE TABLE IF NOT EXISTS book(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
class__id INT,
book_order INT,
title VARCHAR(255),
content TEXT(65535)
) ENGINE=MyISAM;
2)
CREATE TABLE IF NOT EXISTS book_image(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
class__id INT,
type VARCHAR(12),
type__id INT,
image_order INT,
url VARCHAR(50)
) ENGINE=MyISAM;
I need to get a list of books for a given book.class__id, and all images for each of those books with book_image.type = 'book' and book_image.type__id = book.id. Furthermore, the book_images need to be ordered by the image_order column, separately for each book.
I need the resulting object to look somewhat like this:
object(stdClass)
'books' => array (size=2)
0 =>
object(stdClass)
'id' => 13
'class__id' => 55
'book_order' => 1
'title' => xyz
'content' => xyz
'book_images' => array (size=2)
0 =>
object(stdClass)
'id' => 529
'class__id' => 55
'type' => book
'type__id' => 13
'image_order' => 1
'url' => xyz
1 =>
object(stdClass)
'id' => 27
'class__id' => 55
'type' => book
'type__id' => 13
'image_order' => 2
'url' => xyz
1 =>
object(stdClass)
'id' => 21
'class__id' => 55
'book_order' => 2
'title' => xyz
'content' => xyz
'book_images' => array (size=1)
0 =>
object(stdClass)
'id' => 420
'class__id' => 55
'type' => book
'type__id' => 21
'image_order' => 1
'url' => xyz
I'd like to avoid a convoluted foreach() loop with mutliple queries one after the other for each book... I tried various types of joins and select subqueries to no avail.
How do I do this with a single query?

mysql sub query count returning gloabl count and ignoring where

At the moment "matrix_mct_versions" is a table with 73 entries. When I run this query the "version_count" always returns 73, ie the full number of rows. When I run the sub select query on its own i get the real count as per the com_ID param sent. I cannot see what I am doing wrong with this.. can anyone help?
SELECT
a_ID as com_ID,
option_number,
comment,
word_count,
gender,
sample,
(
SELECT
count(a_ID)
FROM
matrix_mct_versions
WHERE
com_ID = com_ID
) as version_count
FROM
matrix_mct
WHERE
attribute_number = :attribute_number AND
grade_number = :grade_number AND
attribute_type = :attribute_type
ORDER BY
option_number
Returns results like this:
[0] => Array
(
[com_ID] => 678
[option_number] => 1
[comment] => TODO primary function missing for controller y
[word_count] => 7
[gender] => 2
[sample] => 0
[version_count] => 73
)
[1] => Array
(
[com_ID] => 679
[option_number] => 2
[comment] => TODO make this green
[word_count] => 4
[gender] => 2
[sample] => 0
[version_count] => 73
)
[2] => Array
(
[com_ID] => 680
[option_number] => 3
[comment] => TODO make this better
[word_count] => 4
[gender] => 2
[sample] => 0
[version_count] => 73
)
At least one problem is your subquery. It is not correlated. I think you mean:
(SELECT count(a_ID)
FROM matrix_mct_versions
WHERE matrix_mct_versions.com_ID = matrix_mct.com_ID
) as version_count