Joins in mysql what to do - mysql

Well I wrote a query and get an error:
Column 'product_id' in field list is ambiguous
Error No: 1052
I need to select the same id from 2 tables and compare them by price here is query I wrote:
$product_sql_test1 = $this->db->query("SELECT `product_id` and 'price' FROM `" . DB_PREFIX . "product_to_category`INNER JOIN (oc_product)ON oc_product.product_id=prdoduct_to_category.product_id WHERE product_to_category.id=product.id and price >150 and `category_id`='".$product_info['related_kv4nt_id_1']."' GROUP BY `product_id` ORDER BY rand() LIMIT 0,10");
Where could be an error and how to fix it? Sorry if the question is too simple.

You have to mention the table name while selecting the product_id because many tables have this column and mysql is confused to select the column from which table
$product_sql_test1 = $this->db->query("SELECT oc_product.`product_id` and 'price'
FROM `" . DB_PREFIX . "product_to_category`INNER JOIN (oc_product)ON
oc_product.product_id=prdoduct_to_category.product_id WHERE product_to_category.id=product.id and price >150 and prdoduct_to_category.`category_id`='".$product_info['related_kv4nt_id_1']."'
GROUP BY oc_product.`product_id` ORDER BY rand() LIMIT 0,10");

Use the full name:
Tablename.ColumnName
For Example in the GROUP BY part it is not clear which product_id you mean.

Both in your Select and your Group By, you need to use your alias table names along with your column names because the same column is present in multiple tables and thus there's a confusion as to which one to use for the result.

Use an Alias name for tables and columns.
Access it like oc.product_id (for column) and oc_product oc(for table)

The correct way to do this is
$product_sql_test1 = $this->db->query("SELECT `p`.`product_id`, `p`.`price` FROM `" . DB_PREFIX . "product_to_category` `p2c` LEFT JOIN `" . DB_PREFIX . "product` `p` ON `p`.`product_id` = `p2c`.`product_id` WHERE `p`.`price` > 150 and `p2c`.`category_id`='" . (int) $product_info['related_kv4nt_id_1'] . "' GROUP BY `p`.`product_id` ORDER BY rand() LIMIT 0,10");
You should also consider formatting your SQL to make it easier to read as well

Related

Pull result for missing data

How to match and product_id in the query
atm the query is pull only missing result but each product have his own record and need to match with this record
This query work right but isn't match product_id
SELECT oc_ekstri_frontend.*,
oc_ekstri_image.id as img_id,
oc_ekstri_image.name
FROM oc_ekstri_image
LEFT JOIN oc_ekstri_frontend ON (oc_ekstri_frontend.id = oc_ekstri_image.frontend_id)
LEFT JOIN oc_ekstri_frontend_view ON (oc_ekstri_frontend_view.ekstri_id = oc_ekstri_image.id)
WHERE oc_ekstri_frontend.subcat_id = '" . $id . "'
AND oc_ekstri_frontend_view.ekstri_id IS NULL
How will I match for current product_id?
I tried something like this to add to the query but isn't work result is empty
AND oc_ekstri_frontend_view.product_id = '" . $product_id . "'
Without seeing your data or your expected output, it is hard to give an exact answer. One possible solution might be to move your new restriction from the WHERE clause to the ON clause:
SELECT
f.*,
i.id AS img_id,
i.name
FROM oc_ekstri_image i
LEFT JOIN oc_ekstri_frontend f
ON f.id = i.frontend_id
LEFT JOIN oc_ekstri_frontend_view v
ON v.ekstri_id = i.id AND
v.product_id = ?
WHERE
f.subcat_id = ? AND
v.ekstri_id IS NULL;
I use ? placeholders in the above query to suggest that you use a prepared statement rather than concatenating in your parameters. If you don't know what prepared statements are in PHP, you should read about them.

Mysql Select one record from another

Hello I have huge problem. In mysql I have 3 tables. Clients , Groups and GroupCross . So I have :
SELECT * FROM clients AS cl
INNER JOIN groupscross AS cr ON cl.cid=cr.cid;
(So now I have matched id in clients with id in groupcross . In groupcross I have also table :cgid .
Now I have data from cr.cgid like : 50,50,60,55,60 so when I command :)
WHERE cr.cgid='function to get id' .
I get all cgid:(50,50,60,55,60)
And here is my question:
How can I do to have all id without 60 ?
I add when I write: WHERE cr.cgid <>60 it shows me all record from database when I want only 50,50,55
Use an IN statement -
SELECT *
FROM `clients` AS `cl`
INNER JOIN `groupscross` AS `cr`
ON `cl`.`cid` = `cr`.`cid`
WHERE `cr`.`cgid` IN(50,55)

How do I combine these three MySQL data queries into one query with multiple columns?

I have these three queries, that I need to combine into one.
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
So I can display them in three columns like this:
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
echo "<td><b>Data Plan: ". $row["currentplan"] . "</b></td> ";
echo "<td><b>Phone Number: ". $row["phonenumber"] . "</b></td> ";
echo "</TABLE>";
}
I have used UNION which just makes one big column with all the data correct which is close, but I need them to all display in one table in three columns. Thank you for any thoughts, if you thought is I should punch myself in the face, already done :)
Use the GROUP BY keyword to create distinct records and sum over the remaining values.
SELECT phonenumber,
dataplan AS currentplan,
SUM(datamb) AS value_sum
FROM maindata
GROUP BY phonenumber, dataplan;
This query will give you unique combinations of phone number and data plan, and will sum the datamb field within these distinct groups. This is great practice for learning the GROUP BY keyword which is very useful for this kind of calculation.
EDIT: When you see a DISTINCT, that's one hint that you can also GROUP BY that field. It means there are likely duplicate values in that column or group of columns. Make sure there's a key defined for this specific group of fields with the same order as the ORDER BY clause for maximum efficiency.
illegal group by in $sql1
please inform yourself on the use of group by.
http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html
query would be
with illegal grouping:
select
SUM(datamb) AS value_sum,
dataplan as "first plan row value in this table for this phone number",
phonenumber AS value_sum1
FROM maindata
group by phonenumber
or without:
select
SUM(datamb) AS value_sum,
dataplan as currentplan ,
phonenumber AS value_sum1
FROM maindata
group by phonenumber, dataplan

Subquery without where-clause

Here's my code
SELECT res.type,
res.contactname,
res.id,
res.inv_addressline2,
res.inv_addressline3,
res.signup_date,
res.engineer_id_global,
res.job_id_global,
res.neg_or_pos,
res.rating,
res.author_id_global,
res.timestamp_global,
res.short_description,
res.job_title,
res.feedback,
author_data.contactname AS `author_name`,
review_count.total_feedback,
review_count.total_rating
FROM (SELECT mb.type,
mb.contactname,
mb.id,
mb.inv_addressline2,
mb.inv_addressline3,
mb.signup_date,
fb.engineer_id AS `engineer_id_global`,
fb.timestamp AS `timestamp_global`,
fb.job_id AS `job_id_global`,
fb.neg_or_pos,
fb.rating,
fb.feedback,
fb.author_id AS `author_id_global`,
ac.engineer_id,
ac.timestamp,
ac.author_id,
jb.job_id,
SUBSTR(jb.job_description, 1, 200) AS `short_description`,
jb.job_title
FROM " . MEMBERS_TABLE . " AS mb
LEFT JOIN " . ACCEPTED . " AS ac
ON mb.id = ac.engineer_id
LEFT JOIN " . FEEDBACK . " AS fb
ON ac.job_id = fb.job_id
LEFT JOIN " . JOBS . " AS jb
ON fb.job_id = jb.job_id
WHERE mb.type = 2
ORDER BY
fb.timestamp DESC
) AS res
LEFT JOIN
(SELECT mb.id,
mb.contactname,
fb.author_id
FROM " . MEMBERS_TABLE . " AS mb
LEFT JOIN " . FEEDBACK . " AS fb
ON fb.author_id = mb.id
LIMIT 1
) AS `author_data`
ON res.author_id_global = author_data.author_id
LEFT JOIN
(SELECT COUNT(fb.engineer_id) AS `total_feedback`,
SUM(fb.rating) AS `total_rating`,
fb.engineer_id
FROM " . FEEDBACK . " AS fb
) AS `review_count`
ON res.engineer_id_global = review_count.engineer_id
GROUP BY res.contactname
ORDER BY res.contactname
I'm just starting to get my head around SQL. My worry is the second and third inner query. Am I right in saying it will return all results as there is no where clause and the return the results from that using the "ON" statement or is the "ON" statement combined with the initial query?
There are a number of issues with this script:
You have a number of tables with names like " . MEMBERS_TABLE . ", " . ACCEPTED . " and so on. These are unlikely to be acceptable in MySQL, which normally uses backticks (`) to quote object names; if this script is to be preprocessed by eg. Perl or Python, or is part of a larger script in another language, it would be helpful to say so.
You have an order by clause, for no apparent reason, in your first sub-query. This could be removed.
Your second sub-query links FEEDBACK to MEMBERS_TABLE and limits the results to 1, without specifying the author_id inside the sub-query - this means that a single, random member will be selected inside the sub-query, then linked to the rest of the dataset on the specific author ID, which won't match for most of the rest of the dataset.
The FEEDBACK table is completely irrelevant here, and can be removed.
If id uniquely identifies a record on MEMBERS_TABLE, the sub-query can be completely removed and replaced with a single left join to MEMBERS_TABLE on res.author_id_global = MEMBERS_TABLE.id. No limit clause would be required.
If id does not uniquely identify a record on MEMBERS_TABLE, the sub-query should be rewritten as select distinct id, contact_name FROM " . MEMBERS_TABLE . " AS mb where res.author_id_global = mb.id LIMIT 1. If there are multiple matching authors for the same id, one would be selected at random.
The third sub-query does not require a where clause - it will summarise all engineers' feedback and ratings by engineer within the sub-query, and each engineer will then be linked to the corresponding engineer from the rest of the dataset by the on condition from the left join clause.
Second inner query is having limit 1. It is nothing but where condition to show only one result. Third inner query is not having any problem.

how to write the sql command in mysql

for example: the table named products there is a product name field in the table. i want to show some related items which matched by the knowed products's product name.
how to write the sql query command?
eg: if the knowed products's product name is
True Blood Season 1 DVD
i want to get all the product name which begins as True Blood Season..
if the knowed products's product name is
24 Hours Season 7 DVD
i want to get all the product name which begins as 24 Hours Season..
the sql: what's error with the sql
$query ="select p.products_id, pd.products_name, p.products_price
from " . TABLE_PRODUCTS . " p " .
TABLE_PRODUCTS_DESCRIPTION . " pd
where p.products_status = 1
and p.products_id = pd.products_id
and pd.language_id = '" . (int)$_SESSION['languages_id'] . "'
and p.products_id <> :product_id AND MATCH('products_name') AGAINST (:products_name IN NATURAL LANGUAGE MODE);
I'd look at using MySQL Full-Text search.
This should be able to take the title of your chosen product and use it to retrieve relevant matches, eg
SELECT * FROM `products`
WHERE `id` <> :product_id -- don't return current product
AND MATCH(`product_name`)
AGAINST (:product_name IN NATURAL LANGUAGE MODE)
This requires you to create a full-text index on your products.product_name column.
select * from products where name like 'True Blood Season%'
select * from products where name like '24 Hours Season%'
SELECT * FROM products WHERE product_name='title of show here';
It's pretty basic SQL, I'd really recommend reading up a bit before posting as this question is very entry level. I'm more than happy to help you get started though :).