I have 3 tables:
place (placeId,placeName,...)
event (eventId, eventName,...)
picture (pictureId,associateId,picturePath,type [1 place 2 event])
This is what I want:
When picture type is 1 picture.associateId=place.placeId return path
when picture type is 2 picture.associateId=event.eventId return path
1 place -> many events
1 place -> one picture
1 event -> one picture
May be something like this (please help):
SELECT Place.placeName, Picture.picturePath, Event.eventId, ... FROM Place INNER JOIN Event ON Place.placeId = Event.eventPlace INNER JOIN Picture ON (IF Picture.type=1 return Picture.picturePath ELSE Picture.type=2 return Picture.picturePath)
This consult return me a json to show events on a page deppending of the date:
SELECT Place.placeName, Place.placePopularity, Picture.picturePath, Event.eventId, Event.eventCount
FROM Place INNER JOIN Picture ON Place.placeId = Picture.associateId
INNER JOIN Event ON Place.placeId = Event.eventPlace
WHERE Picture.type = 2 AND Event.eventDate = '$date'
ORDER BY Event.eventCount DESC
Run an if else with this
if () { // picture type 1
// this is the query
$query = "SELECT pictureTable.picture_path FROM placeTable INNER JOIN picture_table ON placeTable.placeId = picture_table.associateId";
} else { // picture type 2 means for event
$query = "SELECT pictureTable.picture_path FROM eventTable INNER JOIN picture_table ON eventTable.eventId = picture_table.associateId";
// now you can get the result
}
Hope this helps.
Related
I'm creating a planner but the SQL statement I have now only shows employees that have something in table 2 (plannerEntries) and doesn't show the rest of the employees from table 1 (Employee_List).
I need all of the employees to be outputted into the table regardless of whether they have any jobs assigned for them for the week, so that they can have new jobs assigned easily.
This is my current SQL code
SELECT [EL].[Employee_Numer],
[PP].[workDate],
[PP].[jobNo],
[PP].[workDescription],
[PP].[timeOfDay],
[JF].[Description],
[EL].[Forename],
[EL].[Surname]
FROM plannerEntries AS PP
RIGHT JOIN [Employee_List] AS EL
ON [PP].[employeeNumber] = [EL].[Employee_Numer]
INNER JOIN [Job File] AS JF
ON [PP].[jobNo] = [JF].[Job No]
WHERE [PP].[workDate] >= '$monday'
AND [PP].[workDate] <= '$sunday'
ORDER BY [PP].[employeeNumber] ASC;
I expected all employees to be printed regardless of records in table 2, however only the employees with records in table 2 were printed. The below image is the actual output.
Please check the difference between inner join, left join, right join.
Something like this should do what you need:
SELECT
[EL].[Employee_Numer],
[PP].[workDate],
[PP].[jobNo],
[PP].[workDescription],
[PP].[timeOfDay],
[JF].[Description],
[EL].[Forename],
[EL].[Surname]
FROM
[Employee_List] AS EL
left join plannerEntries AS PP on [PP].[employeeNumber] = [EL].[Employee_Numer]
and [PP].[workDate] >= '$monday'
and [PP].[workDate] <= '$sunday'
left join [Job File] AS JF on [JF].[Job No] = [PP].[jobNo]
ORDER BY
[PP].[employeeNumber] ASC;
I need to add a field in one of our query. I'm nt a PHP programmer buy I can get my way around a little. The query is:
if (_QUERYSTRING_) {
switch ($intMode) {
case -1:
$result = mysqli_query($mysql,"
SELECT orders.id,
orders_addresses.strlastname,
orders_addresses.strfirstname,
orders_addresses.intprovince,
9 AS intmode,
Date(orders.dtimeorder) AS datepayment,
orders_costs.dbltotal AS dblamount,
orders_notes.strcod AS strtxn,
0 AS dblfee,
shipping_postalservices.strtracking"._LANG_." as strtrackingurl,
'À recevoir' AS strmode,
NULL AS strvendor
FROM orders
JOIN orders_costs
ON orders_costs.id = orders.id
JOIN orders_addresses
ON orders_addresses.id = orders.id
JOIN orders_notes
ON orders_notes.id = orders.id
JOIN shipping_postalservices
ON shipping_postalservices.id = orders_costs.intpostalservice
WHERE date(orders.dtimeorder) BETWEEN '".date("Y-m-d",$timeStart)."' AND '".date("Y-m-d",$timeEnd)."'
AND orders.boolshipped = 1
AND orders.boolcanceled = 0
AND orders_costs.boolcod = 1
AND orders_costs.dbltotal > 0
AND NOT EXISTS
(
SELECT *
FROM orders_payments
WHERE orders_payments.intorder = orders.id
AND orders_payments.intmode = 9
AND orders_payments.dblamount > 0)
GROUP BY orders.id
ORDER BY orders.dtimeorder,
orders.id");
break;
default:
$result = mysqli_query($mysql,"
SELECT orders.id,
orders_addresses.strlastname,
orders_addresses.strfirstname,
orders_addresses.intprovince,
orders_payments.intmode,
Date(orders_payments.dtimepayment) AS datepayment,
orders_payments.dblamount,
orders_payments.strtxn,
orders_payments.dblfee,
shipping_postalservices.strtracking"._LANG_." as strtrackingurl,
payments.strname"._LANG_." AS strmode,
payments.strvendor
FROM orders_payments
JOIN orders
ON orders.id = orders_payments.intorder
JOIN orders_costs
ON orders_costs.id = orders.id
JOIN orders_addresses
ON orders_addresses.id = orders.id
JOIN shipping_postalservices
ON shipping_postalservices.id = orders_costs.intpostalservice
LEFT JOIN payments
ON payments.id = orders_payments.intmode
WHERE date(orders_payments.dtimepayment) BETWEEN '".date("Y-m-d",$timeStart)."' AND '".date("Y-m-d",$timeEnd)."'".(!empty($intMode) ? "
AND orders_payments.intmode = '".$intMode."'" : NULL)."
GROUP BY orders.id,
orders_payments.intpayment
ORDER BY orders_payments.dtimepayment,
orders.id");
break;
}
The field that needs to be added is orders_addresses.intProvince so it can be displayed in the results. I tried to understand a little but I guess it's a little more complicated than I thought. It does display the province, which are numbers. My question would be, how do I "translate" those numbers by the actual names so it displays "Ontario" instead of 9? The name of the provinces are in another table called Province.
You will need to add another JOIN:
JOIN Province ON orders_addresses.intprovince = Province.x
And in the SELECT part, replace orders_addresses.intprovince by Province.y
where
x = column in table Province that holds the province id
y = column in table Province that holds the province name
So I have a table where some of the products repeat with but have a different value on number of clicks.
name ---- clicks
iPhone 4
Samsung 2
iPhone 1
Samsung 5
my select function is :
$select_table2 = 'SELECT * FROM `mytable`'; //WHERE NAME IS THE SAME
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
I need this output:
iPhone 5
Samsung 7
I don't want to merge the same rows because they have one more column that is different. So please do not suggest simply to merge them and update the clicks...
UPDATE:
$pull_request = 'SELECT SUM(e.product_clicks),e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e GROUP BY e.product_id LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id';
I tried it like this but it's not working
use sum() and also GROUP BY name to get desired output.
$select_table2 = 'SELECT name,SUM(clicks) FROM `mytable` GROUP BY name';
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
while will produce,
iPhone 5
Samsung 7
For more info
SUM()
GROUP BY
EDIT
Group by should come after join.
$pull_request = 'SELECT SUM(e.product_clicks) as clicks,e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e
LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id
GROUP BY e.product_id';
You want to perform a SUM command by group
$query = "SELECT `name`,SUM(`clicks`) FROM `mytable` GROUP BY `name`";
Edit: The other answer was more complete than mine. I forgot to select name field. Added.
What you need is an aggregate function for suming the clicks [SUM(clicks)], and a Group By clause for defining the classification criteria [GROUP BY name].
The other answers where wrong in the sense that are assuming that by changing the select field list adding the aggregate 'SUM', the associative references (eg: index strings of the $row array ) remains the same, the correct query would be:
$select_table2 = 'SELECT name, SUM (clicks) AS clicks FROM mytable GROUP BY name';
Note the alias on SUM(clicks) AS clicks, so the fields returned in the array $row keep their indexes (clicks, names... instead of 'SUM(clicks)')
And the rest is basically the same.
Cheers!
Try :
$select_table2 = 'SELECT name, SUM (clicks) FROM mytable GROUP BY name';
Hello I have this problem and can't find a solution:
I have 4 tables with same structure for example as follows:
Table 1: Result
Table 2: Store 1
Table 3: Store 2
Table 4: Store 3
Tables fields: ID - Code - Name - Value
I need a query to read the "Value" for each specific record from tables (Store 1 - Store 2 - Store 3) and calculate the average and save it in table (Result)...
and go on for the next record until it's done.
Note: I'm using PHP and MySQL...
Thanks in advanced...
SELECT
result.id,
result.`code`,
result.`name`,
result.value,
term1.value,
term2.value,
term3.value
FROM result
INNER JOIN store1 ON result.`code` = store1.`code`
INNER JOIN store2 ON result.`code` = store2.`code`
INNER JOIN store3 ON result.`code` = store3.`code`
WHERE result.`code` = 123456
ORDER BY result.serial ASC
The average is just the sum of the values divided by the number of values (3), this is grade school arithmetic.
UPDATE result AS r
JOIN store1 AS s1 ON s1.code = r.code
JOIN store2 AS s2 ON s2.code = r.code
JOIN store3 AS s3 ON s3.code = r.code
SET r.value = (s1.value+s2.value+s3.value)/3
To do lots of columns, you can generate the SQL in PHP:
$cols = array('col1', 'col2', 'col3', ...);
$sets = implode(', ', array_map(function($col) {
return "r.$col = (s1.$col + s2.$col + s3.$col)/3";
}, $cols));
$sql = "UPDATE result AS r
JOIN store1 AS s1 ON s1.code = r.code
JOIN store2 AS s2 ON s2.code = r.code
JOIN store3 AS s3 ON s3.code = r.code
SET $sets";
If you're using PHP before 5.3.0, you can define a named function to call it with array_map
function make_assignment($col) {
return "r.$col = (s1.$col + s2.$col + s3.$col)/3";
}
$sets = implode(', ', array_map('make_assignment', $cols));
You can create views in MySQL for this. Then there will not need any for this. View is a virtual table. On every change in any table it will automatically updated. You don't need any query
create view result as select t1.code as code,(t1.value+t2.value+t3.value)/3 as value from `testcake`.`test1` as t1 JOIN `testcake`.`test2` as t2 ON t1.code = t2.code JOIN `testcake`.`test3` as t3 ON t1.code = t3.code
I have two tables named patient_list and dentist_list where in the dentist can have many patients, I want to get how many patients the dentist has and ordered it.
I have here a sample code where I get each patient of doctor:
$query_dentist = "SELECT * FROM dentist_list ORDER BY ID ASC";
$res_dentist = mysql_query($query_dentist);
if ($res_dentist) {
while ($row_dentist = mysql_fetch_array($res_dentist)) {
}
}
After I get all the dentists, I create a new query inside the while where I will get all the patient count.
$dentist_id = $row_dentist['id'];
$query_patient= "SELECT COUNT(*) as patient_num FROM patient_list
WHERE dentist_id ='$dentist_id'";
$res_patient=mysql_query($query_patient);
if($res_patient)
{
while($row_patient=mysql_fetch_array($res_patient))
{
}
}
For example the output of query is:
doctor 1 has 10 patient
doctor 2 has 5 patient
doctor 3 has 100 patient
Rather than using PHP, is it possible to use a MySQL statement instead? I will create one query only because i need it to sort by number of patient.
You can try using this code:
select d.Name, -- <- put dentist information here
(select count(1) from patient_list p where p.dentist_id = d.dentist_id)
from dentist_list d
order by 2 asc -- <- order by by the 2nd field that is (select count(1...
SELECT COUNT(*) AS Patient_Num FROM patient_list GROUP BY dentist_id ORDER BY 1