I am trying to write the SQL that selects all products and available features.
My database is as follows:
CREATE TABLE IF NOT EXISTS `products` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(255) NOT NULL,
`product_description` varchar(255) NOT NULL,
`product_weight` varchar(255) NOT NULL,
`product_price` decimal(11,2) NOT NULL,
`product_image` varchar(255) NOT NULL,
PRIMARY KEY (`product_id`)
);
CREATE TABLE IF NOT EXISTS `features` (
`feature_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`feature_uri` varchar(255) NOT NULL,
`feature_name` varchar(100) NOT NULL,
`feature_title` varchar(150) DEFAULT NULL,
`feature_body` text,
`feature_body_short` varchar(255) DEFAULT NULL,
`feature_image` varchar(255) DEFAULT NULL,
`parent_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`feature_id`),
UNIQUE KEY `feature_uri_UNIQUE` (`feature_uri`),
KEY `parentFK` (`feature_id`),
FULLTEXT KEY `feature_name_FT` (`feature_name`),
FULLTEXT KEY `feature_body_FT` (`feature_body`)
);
CREATE TABLE IF NOT EXISTS `feature_products` (
`feature_product_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`feature_product_order` smallint(6) DEFAULT NULL,
`feature_product_standard` tinyint(1) NOT NULL,
`feature_id` int(11) unsigned NOT NULL,
`product_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`feature_product_id`),
KEY `productFK` (`product_id`),
KEY `featureFK` (`feature_id`)
);
I would like to be able to do this in one loop e.g:
{foreach}
<tr>
<td>{name}</td>
<td>{weight}</td>
<td>{if product_id == 1}yes{/if}</td>
<td>{if product_id == 2}yes{/if}</td>
etc
<tr>
{/foreach}
I am using Zend, if this can be of use.
Trying to achieve this HTML:
UPDATE:
Non of the suggested answers are working, instead I managed to hack it to work like this:
SELECT
p.*,
(
SELECT
GROUP_CONCAT(f.feature_id SEPARATOR ', ')
FROM feature_products fp
LEFT JOIN features f ON f.features_id = fp.feature_id
WHERE fp.product_id = p.product_id
LIMIT 1
) as features
FROM product p
Although the problem with the above code is that it does not return 'feature_product_standard'
I'm assuming that you have MySQL, dunno about Zend, but this should get you started.
SELECT
p.product_name
, p.product_description
, p.product_weight
, p.product_price
, p.product_image
, GROUP_CONCAT(f.feature_id ORDER BY f.feature_id) as feature_ids
, GROUP_CONCAT(f.feature_name ORDER BY f.feature_id) as feature_names
FROM products p
LEFT JOIN feature_products fp ON (fp.product_id = p.product_id)
LEFT JOIN features f ON (f.feature_id = fp.feature_id)
GROUP BY p.product_id
Not very good code i know, but i hope it helps.
This is using Johan's SQL code.
I haven't tested this.
$connection = odbc_connect("Connection info here");
$query = "SELECT
p.product_name
, p.product_description
, p.product_weight
, p.product_price
, p.product_image
, GROUP_CONCAT(f.feature_id ORDER BY f.feature_id) as feature_ids
, GROUP_CONCAT(f.feature_name ORDER BY f.feature_id) as feature_names
FROM products p
LEFT JOIN feature_products fp ON (fp.product_id = p.product_id)
LEFT JOIN features f ON (f.feature_id = fp.feature_id)";
$result = odbc_exec($connection, $query);
while ($data[] = odbc_fetch_array($result));
odbc_close($connection);
if ($data[0]["product_name"]) {
echo "<table><tr>";
foreach (array_keys($data[0]) as $a) { $message .= "<th>".$a."</th>"; }
foreach ($data as $d) {
if ($d["product_name"]) {
if ($d) {
echo "</tr><tr>\n";
foreach ($d as $s) {
echo "<td>".$s."</td>";
}
}
}
}
}
Related
I am trying to show the amount of reviews for each restaurant.
I made 2 tables containing my data.
CREATE TABLE `restaurants` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`city` varchar(200) NOT NULL,
`country` varchar(200) NOT NULL,
`score` int(1) NOT NULL DEFAULT '0',
`reviews` int(1) NOT NULL DEFAULT '0',
`slug` varchar(200) NOT NULL DEFAULT 'slug-test',
`approved` int(1) NOT NULL DEFAULT '0',
`description` text NOT NULL,
`review` int(11) DEFAULT '0',
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`img_url` varchar(255) NOT NULL,
`category` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=latin1
CREATE TABLE `reviews` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`restaurant_id` int(11) NOT NULL,
`review_text` text NOT NULL,
`score` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `restaurant_id` (`restaurant_id`),
CONSTRAINT `reviews_ibfk_1` FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
I am already showing my restaurants in a list.
$query = "SELECT * FROM restaurants WHERE approved = 1 ORDER BY created_date DESC";
$result = $mysqli->query($query);
while($row = $result->fetch_array()) {
**HTML WITH MY VARIABLES**
}
This is how u currently show my reviews (hardcoded result in my restaurants table.
if ($reviews <= "0") {
echo "<a href='#' title='Write reviews'><p class='purple-def-color fz-12 mb-0'>write a review</p></a>";
} else if ($reviews > "1") {
echo "<p class='purple-def-color mb-0'>". $row['reviews'] ." reviews</p>";
} else {
echo "<p class='purple-def-color mb-0'>" . $row['reviews'] . " review</p>";
}
I tried to use a JOIN query but was not successful to show the amount of reviews in any way.
Based on your table structure, you can get a review count for each restaurant by joining the reviews table, selecting the COUNT of reviews, and grouping by restaurant ID.
Grouping by restaurant allows you to get an aggregate (e.g. count) of the joined review records for each restaurant.
SELECT
rs.*,
COUNT(rv.`id`) as `reviewCount`
FROM `restaurants` rs
LEFT JOIN `reviews` rv
ON (rv.`restaurant_id` = rs.`id`)
WHERE rs.`approved` = 1
GROUP BY rs.`id`
ORDER BY rs.`created_date` DESC;
Then, when you fetch the rows in PHP, you can reference each row's review count:
echo $row['reviewCount'];
To further demonstrate aggregate functions, here's an example of how to select the average, minimum, and maximum review score for each restaurant:
SELECT
rs.*,
COUNT(rv.`id`) as `reviewCount`,
AVG(rv.`score`) as `reviewAverageScore`,
MIN(rv.`score`) as `reviewMinScore`,
MAX(rv.`score`) as `reviewMaxScore`
FROM `restaurants` rs
LEFT JOIN `reviews` rv
ON (rv.`restaurant_id` = rs.`id`)
WHERE rs.`approved` = 1
GROUP BY rs.`id`
ORDER BY rs.`created_date` DESC;
Try a left join:
$query = 'SELECT * FROM restaurants LEFT JOIN reviews on reviews.restaurant_id = restaurants.id'
A left join returns all records from the left table (restaurants), and the matched records from the right table (reviews)
My business has a simple invoicing system written by me a few years ago in php with a MySQL database. When I wrote it, I knew just enough to be dangerous. While it does work, a lot of the code is very inefficient, slow and poorly conceived, so I'm re-writing some of it in the hopes of fixing it.
There are two tables: customers and transactions. When invoices need to be created, there are two queries, the second unfortunately in a while loop. Here is some simplified pseudo-code to show what I'm doing:
// Get list of customers who owe something
SELECT name, address
FROM customers
WHERE
(SELECT COUNT(*) FROM transactions
WHERE transactions.customer_id = customers.id
AND owed > 0)
> 0
ORDER BY address
//loop through that result and query the transactions table to get a
//list of charges for each customer. Like:
while ($row = customer_array()) {
echo name_and_address;
SELECT * FROM transactions WHERE id = $row['customer_id']
AND owed = TRUE ORDER BY date
while ($row = transactions_array()) {
echo each_transaction_row;
}
So obviously the nested loops, subqueries and queries in loops are bad, worse and slow. I've tried joins but can't seem to figure out how to make them work correctly in this context. What is the correct way to do something like this? Can it be done with a single query?
Table structure:
CREATE TABLE `customer_data` (
`account_id` int(6) NOT NULL AUTO_INCREMENT,
`service_address` varchar(255) DEFAULT NULL,
`service_zipcode` int(5) DEFAULT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`billing_address1` varchar(255) DEFAULT NULL,
`billing_address2` varchar(255) DEFAULT NULL,
`billing_city` varchar(255) DEFAULT NULL,
`billing_state` varchar(2) DEFAULT NULL,
`billing_zipcode` varchar(20) DEFAULT NULL,
`phone1` varchar(100) DEFAULT NULL,
`phone2` varchar(100) DEFAULT NULL,
`quoted_price` int(6) DEFAULT NULL,
`current_price` int(6) DEFAULT NULL,
`original_interval` varchar(10) DEFAULT NULL,
`current_interval` varchar(7) DEFAULT NULL,
`temp_interval` int(5) NOT NULL,
`email` varchar(100) DEFAULT NULL,
`origin_date` varchar(20) DEFAULT NULL,
`remarks` text,
`crew_remarks` text NOT NULL,
`customer_type` varchar(10) DEFAULT NULL,
`perm_crew_assign` int(5) NOT NULL DEFAULT '0',
`temp_crew_assign` int(5) NOT NULL,
`date_last_service` date DEFAULT NULL,
`next_scheduled_date` date DEFAULT NULL,
`excluded_days` varchar(255) NOT NULL,
`special_instructions` text NOT NULL,
`inactive` tinyint(1) NOT NULL DEFAULT '0',
`location` varchar(255) NOT NULL,
`sent_letter` date NOT NULL,
`date_added` datetime NOT NULL,
`email_notify` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`account_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1687 DEFAULT CHARSET=utf8
CREATE TABLE `transactions` (
`transaction_id` int(10) NOT NULL AUTO_INCREMENT,
`account_id` int(6) NOT NULL,
`crew_id` int(3) NOT NULL,
`date_performed` date NOT NULL,
`date_recorded` datetime NOT NULL,
`price` int(6) NOT NULL,
`amount_paid` int(6) NOT NULL,
`description` varchar(255) NOT NULL,
`user` varchar(255) NOT NULL,
`status` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`transaction_id`)
) ENGINE=InnoDB AUTO_INCREMENT=69233 DEFAULT CHARSET=latin1
You can do this with one query and one loop. You can join the two tables and sort the result. Then when the name changes, you know you are starting a new customer.
SELECT c.name, c.address, t.*
FROM customers AS c
JOIN transactions AS t ON (t.customer_id = c.customers.id)
WHERE c.owed > 0
ORDER BY `c`.`name`
// Data looks like this
// | customer.name | customer.address | transaction.* |
$prevName = null;
$prevCustTransList = [];
$prevCustTransTotalOwed = 0;
while ($row = result_array()) { // pseudo code
if ( $row['c.name'] != $prevName ) {
if ( $prevName != null && $prevCustTransTotalOwed > 0 ) {
echo $prevName; // pseudo code
foreach($prevCustTransList as $t) {
echo $t; // pseudo code
}
}
$prevName = $row['c.name'];
$prevCustTransTotalOwed = 0;
$prevCustTransList = [];
}
// Keep the list of transactions to print out later.
$prevCustTransList[] = transaction data; // pseudo code
// Keep a running total of the amount owed
// Replace with actual calculation
$prevCustTransTotalOwed += transaction.price;
}
Yes you can do this in one query, ordering by account_id. In your 'transactions' table account_id should be indexed, since you'll be using it to join to 'customer_data'.
$st_date = '2016-01-01';
$end_date = '2016-02-01';
//select sql
SELECT c.name,c.account_id, ts.*
FROM customer_data c
INNER JOIN transactions ts ON (c.account_id = ts.account_id)
WHERE ts.price > 0 and ts.date_performed between $st_date and $end_data
$current_account_id = null;
while ($row = $results) {
if ($current_account_id != $row['account_id']) {
//print customer name, details, etc..
}
//print the transactions detail
echo $results['transaction_id']; //etc...
//keep track of the current customer
$current_account_id = $row['account_id']
}
first, sorry for my English ...
what i want is to select from two SQL tables and then make them in a specific order , like in forums ...
i have two table, topic and users, i want to select from both of them a putt author info next to his topic
here is the SQL of Topic and users
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`author_id` int(11) NOT NULL,
`timestamp` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and the php code might look like this
<?php
$sql = mysql_query(' MySQL query ... ');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
is there any way to do it ??
As I understood, what you are looking for is the correct SQL statement to execute. The following simple solution will.
<?php
$sql = mysql_query('SELECT users.username, topics.message FROM `users` INNER JOIN topics ON topics.author_id = users.id');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
SELECT * FROM `users` INNER JOIN topics ON topics.author_id = users.id'
I have a photo contest app where users can vote. I would like to select all of the contests where the logged in user has not voted yet.
So I have two tables.
The "contest" table :
CREATE TABLE `contest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`desc` text NOT NULL,
`created_date` datetime NOT NULL,
`started_date` datetime NOT NULL,
`nb_user_min` int(11) NOT NULL,
`nb_photo_max` int(11) NOT NULL,
`nb_photo_per_user` int(11) NOT NULL,
`duration` int(11) DEFAULT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The "contest_vote" table :
CREATE TABLE `contest_vote` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`pic_id` int(11) DEFAULT NULL,
`contest_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`ip` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
So to be clear, I want to get the number (or the list) of contests where the user has not voted yet. So I have tried with a LEFT JOIN but it doesn't return the good set of result. Here it the query I have until now :
SELECT DISTINCT c.id, c.title, cv.user_id
FROM contest c
LEFT JOIN contest_vote cv
ON cv.contest_id = c.id AND cv.user_id != ?
GROUP BY contest_id
("?" represents the user_id parameter).
Can you help me to solve this?
This is pretty simple do with a subquery. Just grab all contest without where user is voted like this:
SELECT DISTINCT c.id, c.title
FROM contest c
WHERE c.id NOT IN (SELECT DISTINCT cv.contest_id FROM contest_vote cv WHERE cv.user_id = ?)
Try this one :
SELECT DISTINCT c.id, c.title, cv.user_id
FROM contest c
LEFT JOIN contest_vote cv ON cv.contest_id = c.id AND cv.user_id != ? WHERE c.user_id = ?
GROUP BY contest_id
I have these 2 queries and i would like to join them into one but i am unsure of how to go about it.
Query 1:
$query = "SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_publisher."='".$pub_id."'
AND ".$db_fld_comics_active."='1' GROUP BY ".$db_fld_comics_arc;
Query 2:
$q2 = mysql_query('SELECT '.$db_fld_arcs_title.' FROM '.$db_tbl_arcs.'
WHERE '.$db_fld_arcs_id.'="'.$result[$db_fld_comics_arc].'"');
Comics Table:
CREATE TABLE IF NOT EXISTS `comics` (
`id` varchar(255) NOT NULL,
`arc` int(255) NOT NULL,
`title` varchar(255) NOT NULL,
`issue` decimal(5,1) DEFAULT NULL,
`price` decimal(10,2) NOT NULL,
`plot` longtext NOT NULL,
`publisher` int(255) NOT NULL,
`isbn` varchar(255) NOT NULL,
`published` date NOT NULL,
`cover` varchar(255) NOT NULL DEFAULT './images/nopic.jpg',
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`views` int(255) NOT NULL DEFAULT '0',
`active` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `arc` (`arc`,`title`,`issue`,`publisher`)
);
Arcs Table:
CREATE TABLE IF NOT EXISTS `arcs` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`plot` longtext NOT NULL,
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`title`)
);
What I need to do is get the Arcs Title from the arcs table for the respective comic arc.
You need to use INNER JOIN for that since I presume that records are present on both tables.
SELECT a.*, b.title
FROM comics a INNER JOIN arcs b
on a.id = b.id
WHERE a.Title = 'VALUEHERE'
displays all details from comics table and the title of the arc
as simple as (joining 2 queries in one, by selecting only the required field and using IN):
SELECT
'.$db_fld_arcs_title.'
FROM '.$db_tbl_arcs.'
WHERE '.$db_fld_arcs_id.' IN (
SELECT '.$db_fld_comics_arc.'
FROM '.$db_tbl_comics.'
WHERE '.$db_fld_comics_publisher.'='".$pub_id."'
AND '.$db_fld_comics_active.'='1' GROUP BY '.$db_fld_comics_arc.'
)