How can I modify this script to delete the records instead of showing them? - mariadb

WITH CTE AS (
SELECT
user_id,
ip_addr,
MIN(reg_date) AS min_reg_date
FROM
user_info
GROUP BY
ip_addr
HAVING
COUNT(*) > 1
)
SELECT
users.id
FROM
users
JOIN user_info
ON users.id = users_info.user_id
JOIN CTE
ON user_info.ip_addr = CTE.ip_addr
AND user_info.reg_date > CTE.min_reg_date;
user_info table:
CREATE TABLE `user_info` (
`user_id` int(11) UNSIGNED NOT NULL,
`ip_addr` varchar(255) DEFAULT NULL,
`user_agent` varchar(255) DEFAULT NULL,
`reg_date` timestamp NOT NULL DEFAULT current_timestamp()
)
users table:
CREATE TABLE `users` (
`id` int(11) UNSIGNED NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`nickname` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL,
`group_id` int(11) UNSIGNED DEFAULT NULL
)
I tried using EXISTS and IN keywords but it shows that the error is near "DELETE FROM..."
Should i change something else ? Please help.

Related

Its my code please any one tell me why wordpress didn't create table in my database

Its my code please any one tell me why wordpress didn't create table in my database:
function xc_create_all_tables(){
global $wpdb;
$cod = $wpdb->prefix."cod_system";
$charset_collate = $wpdb->get_charset_collate();
$data = "CREATE TABLE $cod (
id int NOT NULL AUTO_INCREMENT,
picker_name varchar (255) NOT NULL,
picker_add varchar (255) NOT NULL,
picker_cell varchar (255) NOT NULL,
picker_area varchar (255) NOT NULL,
name varchar (255) NOT NULL,
addd varchar (255) NOT NULL,
cell varchar (255) NOT NULL,
area varchar (255) NOT NULL,
weight varchar (255) NOT NULL,
pd_number varchar (255) NOT NULL,
amount varchar (255) NOT NULL,
status varchar (255) NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $data );
$singlecod = $wpdb->prefix."singlecod_system";
$charset_collate2 = $wpdb->get_charset_collate();
$data2 = "CREATE TABLE $singlecod (
id int NOT NULL AUTO_INCREMENT,
picker_name varchar (255) NOT NULL,
picker_add varchar (255) NOT NULL,
picker_cell varchar (255) NOT NULL,
picker_area varchar (255) NOT NULL,
name varchar (255) NOT NULL,
addd varchar (255) NOT NULL,
cell varchar (255) NOT NULL,
area varchar (255) NOT NULL,
weight varchar (255) NOT NULL,
pd_number varchar (255) NOT NULL,
amount varchar (255) NOT NULL,
status varchar (255) NOT NULL,
PRIMARY KEY (id)
) $charset_collate2;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $data2 );
}

Multi level Marketing stored procedure in SQL Server

Tree Image
I want to create a multilevel tree structure for user Registration , a members can add up to 5 members if he adds another member which greater than the limit it should be added as the first child member. for example as in the figure tree Image, 1 can directly add members 2,3,4,5,6 if 1 add a member again it should be added as the first child of 2,and if 1 add again it should be added as the first child of 3 and so on up to first child of 6, then if one again adds it should be the second child of 2, again second child of 3 and so on how can i create a stored procedure to insert into my user table which automatically perform this here i am attaching my table structure also
Here I am attaching the table how can i achieve this
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Login_ID] [uniqueidentifier] NOT NULL,
[Login_Name] [nvarchar](100) NOT NULL,
[Login_Password] [nvarchar](100) NOT NULL,
[CreatedBy] [uniqueidentifier] NULL,
[ModifiedBy] [uniqueidentifier] NULL,
[Referal_ID] [uniqueidentifier] NULL,
[Name] [nvarchar](100) NULL,
[User_Address] [nvarchar](max) NULL,
[Phone] [nvarchar](14) NULL,
[Email] [nvarchar](100) NULL,
[BankName] [nvarchar](250) NULL,
[AccountName] [nvarchar](100) NULL,
[IFSC] [nvarchar](100) NULL,
[AccountNo] [nvarchar](150) NULL,
[DOB] [datetime] NULL,
[Created_Date] [datetime] NULL,
[Modified_Date] [datetime] NULL,
[Last_Login_Date_Time] [datetime] NULL,
[UnsuscribeEmail] [int] NULL,
[UnsuscribeSms] [int] NULL,
[IsBanned] [int] NULL,
[ISDeleted] [int] NULL,
PRIMARY KEY CLUSTERED ([Login_ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
USE [Hyperbole]
GO
/****** Object: Table [dbo].[Users] Script Date: 9/26/2016 1:22:23 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
[Login_ID] [bigint] IDENTITY(1,1) NOT NULL,
[Login_Name] [nvarchar](100) NOT NULL,
[Login_Password] [nvarchar](100) NULL,
[CreatedBy] [bigint] NULL,
[ModifiedBy] [bigint] NULL,
[Referal_ID] [bigint] NULL,
[Name] [nvarchar](250) NULL,
[User_Address] [nvarchar](max) NULL,
[Phone] [nvarchar](14) NULL,
[Email] [nvarchar](250) NULL,
[BankName] [nvarchar](250) NULL,
[AccountName] [nvarchar](250) NULL,
[IFSC] [nvarchar](250) NULL,
[AccountNo] [nvarchar](250) NULL,
[DOB] [datetime] NULL,
[Created_Date] [datetime] NULL,
[Modified_Date] [datetime] NULL,
[Last_Login_Date_Time] [datetime] NULL,
[UnsuscribeEmail] [int] NULL,
[UnsuscribeSms] [int] NULL,
[IsBanned] [int] NULL,
[ISDeleted] [int] NULL,
PRIMARY KEY CLUSTERED
(
[Login_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Stored Procedure
CREATE Proc [dbo].[User_SP]
(
#Login_Name nvarchar(100)=null
,#Login_Password nvarchar(100)=null
,#CreatedBy BIGINT=null
,#ModifiedBy BIGINT=null
,#Referal_ID BIGINT=null
,#Name nvarchar(250)=null
,#User_Address nvarchar(max)=null
,#Phone nvarchar(14)=null
,#Email nvarchar(250)=null
,#BankName nvarchar(250)=null
,#AccountName nvarchar(250)=null
,#IFSC nvarchar(250)=null
,#AccountNo nvarchar(150)=null
,#DOB datetime=null
,#Created_Date datetime=null
,#Modified_Date datetime=null
,#Last_Login_Date_Time datetime=null
,#UnsuscribeEmail int=0
,#UnsuscribeSms int=0
,#IsBanned int=0
,#ISDeleted int=0
)
--#UserName NVARCHAR (255),
--#parentID BIGINT
as
begin
IF OBJECT_ID('tempdb..#ChildHierarchy') IS NOT NULL
DROP TABLE #ChildHierarchy
IF OBJECT_ID('tempdb..#ChildCount') IS NOT NULL
DROP TABLE #ChildCount
CREATE TABLE #ChildHierarchy ( ChildId BIGINT, ChildName NVARCHAR(255), LevelNo BIGINT, ParentID BIGINT )
CREATE TABLE #ChildCount ( ChildParentID BIGINT, ChildCount BIGINT, ChildParentLevelID BIGINT, MaxChildCount BIGINT, AvailableChildCount BIGINT )
DECLARE #MaxChildCount TABLE ( LevelID INT, MaxChildCount BIGINT )
DECLARE #NextParentID BIGINT, #MaxLevelNo INT
INSERT INTO #MaxChildCount (LevelID, MaxChildCount)
VALUES ( 1, 5 ), ( 2, 25 ), ( 3, 125 ), ( 4, 625 ), ( 5, 3125 ), ( 6, 15625 ), ( 7, 78125 ), ( 8, 390625 ), ( 9, 1953125 ), ( 10, 9765625 )
/*row generations*/
;WITH Hierarchy(ChildId, ChildName, LevelNo, ParentId)
AS
(
SELECT Login_ID, Name, 0, Referal_ID
FROM Users AS FirtGeneration
WHERE Login_ID = #Referal_ID
UNION ALL
SELECT NextGeneration.Login_ID, NextGeneration.Name, Parent.LevelNo + 1, Parent.ChildId
FROM Users AS NextGeneration
INNER JOIN Hierarchy AS Parent ON NextGeneration.Referal_ID = Parent.ChildId
)
INSERT INTO #ChildHierarchy (ChildId,ChildName,LevelNo,ParentID)
SELECT ChildId, ChildName, LevelNo, ParentId
FROM Hierarchy
OPTION(MAXRECURSION 32767)
INSERT INTO #ChildCount (ChildParentID, ChildCount,ChildParentLevelID)
SELECT ParentID, COUNT(ChildId), LevelNo
FROM #ChildHierarchy
WHERE LevelNo > 0
GROUP BY ParentID, LevelNo
UPDATE CC SET MaxChildCount = MCC.MaxChildCount
FROM #ChildCount CC
INNER JOIN #MaxChildCount MCC ON CC.ChildParentLevelID = MCC.LevelID
SET #MaxLevelNo = ( SELECT MAX(LevelNo) FROM #ChildHierarchy )
UPDATE CC SET AvailableChildCount = CC1.AvailableChildCount
FROM #ChildCount CC
INNER JOIN ( SELECT ChildParentLevelID,SUM(ChildCount) AS AvailableChildCount FROM #ChildCount GROUP BY ChildParentLevelID ) CC1 ON CC.ChildParentLevelID = CC1.ChildParentLevelID
IF #MaxLevelNo = 0 OR NOT EXISTS ( SELECT TOP 1 1 FROM #ChildCount )
SET #NextParentID = #Referal_ID
IF #NextParentID IS NULL
SET #NextParentID = ( SELECT MIN(ChildParentID) FROM #ChildCount WHERE MaxChildCount <> AvailableChildCount AND ChildCount <> 5 )
IF #NextParentID IS NULL
SET #NextParentID = ( SELECT MIN(CH.ChildId) FROM #ChildHierarchy CH WHERE NOT EXISTS ( SELECT TOP 1 1 FROM #ChildCount CC WHERE CH.ChildId = CC.ChildParentID ) )
INSERT INTO Users (Login_Name,Login_Password,CreatedBy,ModifiedBy,Referal_ID,Name,User_Address,Phone,Email,BankName,AccountName,IFSC,AccountNo,DOB,Created_Date,Modified_Date,UnsuscribeEmail,UnsuscribeSms,IsBanned,ISDeleted)
SELECT #Login_Name,#Login_Password,#NextParentID,#NextParentID,#NextParentID,#Name,#User_Address,#Phone,#Email,#BankName,#AccountName,#IFSC,#AccountNo,#DOB,#Created_Date,#Modified_Date,0,0,0,0
end
GO

create new table - missing parenthesis

need to create this but its saying missing left parenthesis?
CREATE TABLE
active_units2(agency_code varchar2(10) not null,
unit varchar2(10) not null,
supp_unit_1 varchar2(10) not null,
supp_unit_2 varchar2(10) not null,
supp_unit_3 varchar2(10) not null,
supp_reqmt varchar2(10) not null,
alt_priority varchar2(1) not null,
alt_group varchar2(1) not null,
crew_type varchar2(10) not null,
status_control varchar2(1) not null,
onduty_status varchar2(10) not null,
dependant_res_type varchar2(10) not null,
mdt_state varchar2(10) not null,
brigade int not null,
node int not null,
port int not null,
breathing_apparatus int not null,
manual_crewing int not null,
udf1 varchar2(10) not null,
udf2 varchar2(10) not null,
udf3 varchar2(10) not null,
udf4 varchar2(10) not null,
CONSTRAINT active_units2_PK PRIMARY KEY CLUSTERED (agency_code ,unit))
When you run that statement in SQL*Plus the output you get is:
CONSTRAINT active_units2_PK PRIMARY KEY CLUSTERED (agency_code ,unit))
*
ERROR at line 24:
ORA-00906: missing left parenthesis
The * indicates where the problem is - not always helpful but it is in this case. The CLUSTERED key word isn't valid in Oracle, as you can see from the syntax diagram, so you just need to remove that word.

How to optimize the T-SQL query

I am writing a T-SQL Query, I am developing the e-commerce website, in that I am using 4 major tables:
ProductCategory
Product
OrderLineItem
Order
I have a one page in my admin section for manage the orders, Now I want to filter by ProductCategory i.e. which Order contains the Product (my productId is in OrderLineItem table) which is related to the selected ProductCategory, I am doing this via below query:
SELECT
O.OrderID,O.[OrderDate],O.[StatusID]
FROM [Order] O
INNER JOIN [Dyve_User] U ON U.[UserID] = O.[UserID]
INNER JOIN (SELECT OD.OrderID
FROM OrderLineItem OD
LEFT OUTER JOIN [Product] P ON OD.ProductID = P.ProductID
LEFT OUTER JOIN [ProductCategory] PC ON PC.CategoryID = P.CategoryID
WHERE
(P.CategoryID = COALESCE(#CategoryID, P.CategoryID)
OR P.CategoryID IN (SELECT CategoryID
FROM ProductCategory
WHERE ParentID = COALESCE(#CategoryID, ParentID)
)
)
) AS T ON O.OrderID = T.OrderID
My this query return the correct result but the query times out every time, can any one tell me how to optimize this query so this will not time out?
following is the tables schema:
CREATE TABLE [dbo].[Order](
[OrderID] [int] IDENTITY(1,1) NOT NULL,
[OrderDate] [datetime] NULL,
[OrderTax] [money] NULL,
[OrderTotal] [money] NULL,
[ShippingCharge] [money] NULL,
[TrackingNumber] [varchar](50) NULL,
[TransactionStatusID] [int] NULL,
[UserID] [int] NULL,
[PromotionCode] [varchar](50) NULL
[ExpiryDate] [datetime] NULL,
[PaymentType] [tinyint] NULL
CONSTRAINT [Order_PK] PRIMARY KEY CLUSTERED
(
[OrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Product Table:
CREATE TABLE [dbo].[Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[CategoryID] [int] NULL,
[ProductName] [nvarchar](600) NULL,
[ManufacturerID] [int] NULL,
[UnitPrice] [money] NULL,
[RetailPrice] [money] NULL,
[IsOnSale] [bit] NOT NULL,
[ExpiryDate] [datetime] NULL,
[IsElectrical] [bit] NULL,
[IsActive] [bit] NULL,
[ProductType] [int] NULL,
[AllowBackOrder] [bit] NULL
CONSTRAINT [Product_PK] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ProductCategory Table:
CREATE TABLE [dbo].[ProductCategory](
[CategoryID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Description] [nvarchar](max) NULL,
[ParentID] [int] NULL,
[IsActive] [bit] NULL
CONSTRAINT [ProductCategory_PK] PRIMARY KEY CLUSTERED
(
[CategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
OrderLineItem Table:
CREATE TABLE [dbo].[OrderLineItem](
[OrderDetailID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NOT NULL,
[ProductID] [int] NOT NULL
[TotalPrice] [money] NULL,
[Quantity] [int] NULL,
[Discount] [money] NULL,
[UnitPrice] [money] NULL,
[UserID] [int] NULL,
CONSTRAINT [OrderLineItem_PK] PRIMARY KEY CLUSTERED
(
[OrderDetailID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
A couple of things to start with:
Define indexes on the join and where columns.
Join from the smaller tables to the bigger ones.
I suggest reading up on performance and how to find causes - here is a good article on the subject: part 1 and part 2.
This is not tested so I'm not sure if it still does what you intended with your query.
It will fetch the Orders that has an OrderLineItem with a Product with a CategoryID that is equal to #CategoryID or a child category to #CategoryID.
SELECT O.OrderID,
O.[OrderDate],
O.[StatusID]
FROM [Order] AS O
WHERE O.OrderID IN (SELECT OD.OrderID
FROM OrderLineItem AS OD
INNER JOIN Product AS P
ON OD.ProductID = P.ProductID
INNER JOIN (SELECT PC.CategoryID
FROM ProductCategory
WHERE ParentID = #CategoryID
UNION ALL
SELECT #CategoryID) AS C
ON P.CategoryID = C.CategoryID)
With regards to performance you just have to test it to find out.
Indexes is a good thing and you should make sure that you have indexes on your foreign key columns.
First try to make longer timeout to see it work. Than take a loot at your execution plan. Move tables with less elements to the left of the join.

insert statement conflicted with the foreign key constraint?

my stored procedure is-
CREATE PROCEDURE [dbo].[usp_SetMenu](
#locationId BIGINT,
#menuId BIGINT = NULL,
#name VARCHAR(100) = NULL,
#taxable BIT = NULL,
#type VARCHAR(100) = NULL,
#dateFrom DATETIME = NULL,
#dateTo DATETIME = NULL,
#timeFrom VARCHAR(10) = NULL,
#timeTo VARCHAR(10) = NULL,
#price MONEY = NULL,
#discountPerc FLOAT = NULL,
#discTimeFrom VARCHAR(10) = NULL,
#discTimeTo VARCHAR(10) = NULL,
#textcolor varchar(10) = null,
#bodycolor varchar(10) = null,
#createdBy BIGINT = NULL,
#createdOn DATETIME = NULL,
#modifiedBy BIGINT = NULL,
#modifiedOn DATETIME = NULL,
#menuProductsXML NTEXT = NULL ,
#IsCopy VARCHAR (10) = NULL,
#CopyMenuId BIGINT = NULL,
#menuTaxXML NTEXT = NULL ,
#menuExists INT = NULL OUTPUT,
#newMenuId INT = NULL OUTPUT
)
AS
SET NOCOUNT ON
---------------------------------------------------------------------
-- Declarations of variables
---------------------------------------------------------------------
DECLARE #ptrHandle INT
---------------------------------------------------------------------
-- initialize variables
---------------------------------------------------------------------
---------------------------------------------------------------------
-- get the data
---------------------------------------------------------------------
IF(#menuId IS NULL) -- If menuid is null then create a new record
BEGIN
select #menuExists = count('x') from tblMenu
where [name] = #name and isDeleted = 0 and locationid=#locationId
if #menuExists > 0
Return
INSERT INTO tblMenu
(locationid
,[name]
,[type]
,taxable
,datefrom
,dateto
,timefrom
,timeto
,price
,discountperc
,disctimefrom
,disctimeto
,bodycolor
,textcolor
,createdby
,createdon)
VALUES
(#locationId
,#name
,#type
,#taxable
,#dateFrom
,#dateTo
,#timeFrom
,#timeTo
,#price
,#discountPerc
,#discTimeFrom
,#discTimeTo
,#bodycolor
,#textcolor
,#createdBy
,#createdOn)
SET #menuId = ##IDENTITY
END
ELSE -- If menuid is not null then update that record
select #menuExists = count('x') from tblMenu
where [name] = #name and MenuId <> #menuId and isDeleted = 0 and locationid=#locationId
if #menuExists > 0
Return
UPDATE tblMenu
SET locationid = #locationId
,[name] = #name
,[type] = #type
,taxable = #taxable
,datefrom = #dateFrom
,dateto = #dateTo
,timefrom = #timeFrom
,timeto = #timeTo
,price = #price
,discountperc = #discountPerc
,disctimefrom = #discTimeFrom
,disctimeto = #discTimeTo
,bodycolor = #bodycolor
,textcolor = #textcolor
,modifiedby = #modifiedBy
,modifiedon = #modifiedOn
WHERE menuid = #menuId
-- if menu product collection is passed then insert new records
IF(#menuProductsXML IS NOT NULL)
BEGIN
-- Clearing the old menu products and inserting new ones
DELETE tblMenuProduct WHERE menuid = #menuId
EXEC sp_xml_preparedocument #ptrHandle OUTPUT, #menuProductsXML
INSERT INTO tblMenuProduct
(menuid
,productid
,categoryid
,productprice
,createdby
,createdon)
SELECT #menuId,
ProductId,
CategoryId,
ProductPrice,
#createdBy,
#createdOn
FROM OPENXML (#ptrHandle, '/ArrayOfMenuProductEntity/MenuProductEntity', 2)
WITH(ProductId BIGINT,CategoryId BIGINT, ProductPrice MONEY)
END
if(#IsCopy = 'True')
Begin
INSERT INTO tblMenuProduct
(menuid
,productid
,categoryid
,productprice
,createdby
,createdon)
Select #menuId,productid,categoryid,productprice,#createdBy,#createdOn
From tblMenuProduct where menuid = #CopyMenuId
SET #newMenuId = #menuId
End
IF(#menuTaxXML IS NOT NULL)
BEGIN
DELETE tblMenuTaxClass WHERE menuid = #menuId
EXEC sp_xml_preparedocument #ptrHandle OUTPUT, #menuTaxXML
INSERT INTO tblMenuTaxClass
(menuid
,taxclassid
)
SELECT #menuId,
TaxClassId
FROM OPENXML (#ptrHandle, '/ArrayOfTaxClassEntity/TaxClassEntity', 2)
WITH(TaxClassId BIGINT)
END
---------------------------------------------------------------------
-- exit the sproc
---------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
SET NOCOUNT OFF
END
Exception:insert statement conflicted with the foreign key constraint
Why I am getting this exception and how can I fix this?
The primary key value wont be there.you are trying to insert a Foreign key value to the table where corresponding PK wont be there.
table1
ID(PK)
1
2
3
table2
ID1(PK) ID(FK)
1 1
2 1
3 4// Error not there in PK table

Resources